重排链表问题

本文参考代码随想录

思路

方法一

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

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
        ```
相关推荐
I_LPL4 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
m0_672703318 小时前
上机练习第51天
数据结构·c++·算法
仰泳的熊猫8 小时前
题目2577:蓝桥杯2020年第十一届省赛真题-走方格
数据结构·c++·算法·蓝桥杯
灰色小旋风9 小时前
力扣13 罗马数字转整数
数据结构·c++·算法·leetcode
ccLianLian10 小时前
数论·欧拉函数
数据结构·算法
会编程的土豆11 小时前
C++中的 lower_bound 和 upper_bound:一篇讲清楚
java·数据结构·算法
HUTAC11 小时前
关于进制转换及其应用的算法题总结
数据结构·c++·算法
小刘不想改BUG12 小时前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table
XW010599912 小时前
6-函数-1 使用函数求特殊a串数列和
数据结构·python·算法
沉鱼.4412 小时前
枚举问题集
java·数据结构·算法