重排链表问题

本文参考代码随想录

思路

方法一

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

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
        ```
相关推荐
yyy(十一月限定版)20 小时前
算法——二分
数据结构·算法
啊董dong21 小时前
noi-2026年1月07号作业
数据结构·c++·算法·noi
星火开发设计21 小时前
二叉树详解及C++实现
java·数据结构·c++·学习·二叉树·知识·期末考试
仍然.1 天前
JavaDataStructure---排序
数据结构·算法·排序算法
代码游侠1 天前
应用——MQTT客户端开发
服务器·c语言·开发语言·数据结构·算法
POLITE31 天前
Leetcode 142.环形链表 II JavaScript (Day 10)
javascript·leetcode·链表
独自破碎E1 天前
链表中的节点每k个一组翻转
数据结构·链表
cookqq1 天前
MySQL 5.7 大表删除部分数据:.ibd 文件会变小吗?磁盘会释放吗?
数据结构·数据库·mysql
D_FW1 天前
数据结构第三章:栈、队列与数组
数据结构·算法
福楠1 天前
模拟实现stack、queue、priority_queue
c语言·开发语言·数据结构·c++