重排链表问题

本文参考代码随想录

思路

方法一

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

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
        ```
相关推荐
Fine姐6 小时前
数据结构——02队列
数据结构
仰泳的熊猫6 小时前
1176 The Closest Fibonacci Number
数据结构·c++·算法·pat考试
一条大祥脚6 小时前
Cuda Rudece算子实现(附4090/h100测试)
java·数据结构·算法
2401_841495647 小时前
【LeetCode刷题】跳跃游戏
数据结构·python·算法·leetcode·游戏·贪心算法·数组
_w_z_j_8 小时前
全排列问题(包含重复数字与不可包含重复数字)
数据结构·算法·leetcode
@小码农8 小时前
LMCC大模型认证 青少年组 第一轮模拟样题
数据结构·人工智能·算法·蓝桥杯
CoderYanger9 小时前
A.每日一题——3606. 优惠券校验器
java·开发语言·数据结构·算法·leetcode
coderxiaohan9 小时前
【C++】哈希表实现
数据结构·哈希算法·散列表
CoderYanger9 小时前
D.二分查找-基础——744. 寻找比目标字母大的最小字母
java·开发语言·数据结构·算法·leetcode·职场和发展