重排链表问题

本文参考代码随想录

思路

方法一

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

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
        ```
相关推荐
开发小能手1237 小时前
答案daanC语言
数据结构·算法
启观川10 小时前
数据结构与算法-第 3 章 常用算法-贪心算法
数据结构·笔记·python·算法·贪心算法
程序员清风11 小时前
堆与优先队列:从 Top K 到任务调度
java·数据结构·算法
suhan11 小时前
【数据结构】四、串:串string、模式匹配BF\KMP、广义表
数据结构·后端·算法
啵啵啵鱼12 小时前
第二章 线性表
java·数据结构·算法
局部有解12 小时前
Hot100 - 三数之和
数据结构·c++·算法
辉艺棉麻小张12 小时前
用 JSON 建模面料规格:成分、克重、支数与公定回潮率字段设计
数据结构
longlongzihan12 小时前
C++ 常用数据结构速查:vector、stack、queue、list、树、图、哈希表等声明与核心操作
数据结构·c++·list
爱读书的小胖16 小时前
LeetCode 27. 移除元素(C)解题分析
数据结构·算法
爱读书的小胖17 小时前
Codewars: A Brave New Wordle(C)解题分析
c语言·数据结构·算法