重排链表问题

本文参考代码随想录

思路

方法一

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

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
        ```
相关推荐
洋不写bug4 分钟前
链表补充练习,双链表的模拟实现
java·数据结构·链表·双链表·底层实现
白狐_79842 分钟前
408 数据结构|外部排序:流程与 k 路归并
数据结构·算法
heima20161 小时前
长期复盘:拼团活动链接开发公司的行业现状与困境洞察
链表
mmmmath_32 小时前
面试题 02.07. 链表相交
算法·链表
sylviiiiiia3 小时前
Leetcode hot100 多数元素/相交链表/反转链表
算法·leetcode·链表
我不会起名字3223 小时前
一天一道算法题(26):栈的简单应用
java·数据结构·python·算法·leetcode·golang·
不会就选b3 小时前
算法日常・每日刷题--<贪心+大根堆>2
数据结构·算法
事圆则缓4 小时前
Java 常见数据结构与 Android 使用场景
android·java·数据结构
白狐_7984 小时前
408 数据结构|外部排序优化:怎么减少时间开销
数据结构·算法
kiracrimson17 小时前
从缓存的角度看链表与线性表的差异
数据结构·链表·缓存