leetcode 61(旋转链表) & 143(Reorder List)

本文深入讲解了链表的两种高级操作技巧:旋转链表和重新排序链表。通过双指针法实现链表的旋转,以及如何通过初始化慢快指针进行链表的中间元素定位,进而反转链表后半部分并两两相连。适合对链表操作有一定基础的读者进一步提升技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
思路:双指针。以图中例子,k= 2时,其实是把4后的链表放到前边,类似前面找到倒数第n个数

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next:
            return head
        slow = fast = dummy = ListNode(-1)
        dummy.next = head
        count = 0
        cur = head
        while cur:
            count += 1
            cur = cur.next
        if k >= count:
            k = k % count

        if k > 0:
            for _ in range(k):
                fast = fast.next
            while fast.next:
                fast = fast.next
                slow = slow.next
            dummy.next = slow.next
            fast.next = head
            slow.next = None
        return dummy.next

在这里插入图片描述

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        # 初始化slow = head, fast = head.next,此后fast一次走两步,slow一次走一步,直到,fast下一步或下两步为None
        # 经过上面的步骤,slow刚好是中间那个数(链表为奇数时如7,slow为3,链表为偶数时如8,slow为4)
        # 为什么上述步骤后,slow为中间数。设链表长度为n,则fast会走 (n-1) // 2步,同时,slow也走同样的步数。
        # 以n = 8为例,fast从第二数走 7//2=3大步,每大步为两小步,fast走到8,slow从1开始走3小步后到4
        # 划分左右两边,以slow为分界线,左边包含slow,右边从slow.next开始,为了使右边包含slow,上述循环后令slow = slow.next
        # 反转右边的链表
        # 将左右两边两两相连
        if not head or not head.next:
            return
        slow = head
        fast = head.next
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        slow = slow.next # 使slow表示为右边
        if fast.next:
            fast = fast.next
        # 反转右边的链表
        pre = ListNode(-1)
        pre.next = slow
        cur = slow
        nex = cur.next
        while nex:
            cur.next = nex.next
            nex.next = pre.next
            pre.next = nex
            nex = cur.next
        
        # 反转链表后fast变为右边链表的第一个
        
        # 将左右两边连接起来,注意此时左边仍为整个链表
        trav = head
        while fast.next:
            temp1 = trav.next
            temp2 = fast.next
            trav.next = fast
            fast.next = temp1
            fast = temp2
            trav = temp1
        
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱编程的喵喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值