重排链表问题

本文参考代码随想录

思路

方法一

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

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
        ```
相关推荐
旖-旎2 分钟前
哈希表(存在重复元素||)(4)
数据结构·c++·算法·leetcode·哈希算法·散列表
被摘下的星星10 分钟前
数据结构中逻辑结构和存储结构对应有哪些
数据结构
磊 子24 分钟前
八大排序之冒泡排序+选择排序
数据结构·算法·排序算法
潇洒畅想30 分钟前
1.1 从∑到∫:用循环理解求和与累积
java·数据结构·python·算法
计算机安禾1 小时前
【数据结构与算法】第41篇:图论(五):拓扑排序与关键路径
c语言·数据结构·c++·算法·图论·visual studio
玉树临风ives2 小时前
atcoder ABC 453 题解
数据结构·c++·算法·图论·atcoder
琪伦的工具库3 小时前
批量PDF合并工具使用说明:批量合并与直接合并两种模式,拖拽排序/页面范围/遍历子目录/重名自动处理
数据结构·pdf·排序算法
山甫aa3 小时前
哈希集合-----从零开始的数据结构学习
数据结构·算法·哈希算法
say_fall3 小时前
有关算法的简单数学问题
数据结构·c++·算法·职场和发展·蓝桥杯
小杰帅气3 小时前
算法的时间和空间复杂度
数据结构