重排链表问题

本文参考代码随想录

思路

方法一

把链表放进双向队列,然后通过双向队列一前一后弹出数据,来构造新的链表。

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        d = collections.deque()
        tmp = head
        while tmp.next:
            d.append(tmp.next)
            tmp = tmp.next
        tmp = head
        while len(d):
            tmp.next = d.pop()
            tmp = tmp.next
            if len(d):
                tmp.next = d.popleft()
                tmp = tmp.next
        tmp.next = None
        

方法二

将链表分割成两个链表,然后把第二个链表反转,之后在通过两个链表拼接成新的链表。

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        fast, slow = head, head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next

        right = slow.next
        slow.next = None
        right = self.reverseList(right)
        left = head

        while right:
            curLeft = left.next
            left.next = right
            left = curLeft

            curRight = right.next
            right.next = left
            right = curRight

    def reverseList(self, head):
        cur = head
        pre = None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre
        ```
相关推荐
smj2302_796826528 小时前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
梓䈑10 小时前
【算法题攻略】快速排序 和 归并排序
数据结构·c++·排序算法
he___H12 小时前
leetcode100-普通数组
java·数据结构·算法·leetcode
不知名的老吴13 小时前
经典算法实战:重新排列日志文件(二)
数据结构·算法
CS创新实验室13 小时前
数据结构和算法:斐波那契堆
数据结构·算法·斐波那契堆
guslegend15 小时前
2.Redis核心数据结构
数据结构·数据库·redis
Daydream.V15 小时前
Redis 零基础入门到实战:数据结构 + 常用命令 + 场景全覆盖
数据结构·数据库·redis
bnmoel15 小时前
数据结构深度剖析二叉树・中篇:堆的概念及结构 ,实现应用全解析
数据结构·算法·二叉树··top-k问题
fu的博客15 小时前
【数据结构15】哈夫曼树构建、编码(附手绘图解)
数据结构
bnmoel15 小时前
数据结构深度剖析二叉树・上篇:基础概念、结构特性、存储结构全解析
c语言·数据结构·二叉树·