重排链表问题

本文参考代码随想录

思路

方法一

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

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
        ```
相关推荐
悠仁さん10 分钟前
数据结构 图(代码实现篇 C语言版)
数据结构·算法·图论
Shadow(⊙o⊙)2 小时前
专题四:前缀和
数据结构·算法
Tisfy2 小时前
LeetCode 2095.删除链表的中间节点:两次遍历 / 一次遍历(快慢指针)
算法·leetcode·链表·题解·双指针
Irissgwe2 小时前
AVL树详解
数据结构·c++·算法·二叉树·c·二叉搜索树·avl
北域码匠2 小时前
奇偶归并排序:并行计算的排序利器
数据结构·算法·c#·排序算法
玖玥拾3 小时前
C/C++ 数据结构(五)链表的应用、对象池
c语言·数据结构·c++·链表·对象池·双向链表
2601_961845153 小时前
花生十三网课网盘|百度网盘|下载
数据结构·算法·链表·贪心算法·排序算法·线性回归·动态规划
郝学胜_神的一滴4 小时前
完全二叉树与堆底层原理深度剖析 | 手写C++大顶堆实现
数据结构·算法
asdzx674 小时前
Python 优雅解析 Excel:从原生行列到强类型对象的三层数据结构演进
数据结构·python·excel
是苏浙4 小时前
Java实现链表2
java·开发语言·数据结构