【MT-链表】92

本文详细介绍了如何通过四步操作实现链表中指定区间的反转。首先定位窗口范围,然后移动窗口到正确位置,接着反转窗口内的节点,最后将反转后的部分与外部节点连接起来。文章还提供了一种优雅地处理边界情况的方法。

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

92. 反转链表 II
Step1:
The part I need to reversed is node 2 to node 4, which has n - m + 1 = 3 nodes.
Therefore, I would like to maintain a window with n - m + 1 nodes with the window’s head whead and window’s tail wtail, then if whead is head, wtail would be the next n-m node from head.

[123]45 => whead is 1 and wtail is 3
Step2:
And to get to the right reversed portion we want, we need to shift the window m-1 times

1[234]5 => whead is 2 and wtail is 4
Step3: Isolate the nodes inside the window, reverse the window as Reverse Linked List

Step4: combine the outside node with reversed node.
To do so, I need to record the head outside the window ohead, and the tail outside the window otail

ohead is 1, otail is 5
1-[432]-5
Implementation detail: Since in step 4, you need to let ohead.next = reversed_headIf you create a dummy node, you can save some lines for m == 1 cases, where ohead would be None and ohead.next would fail the program.
参考链接

    def reverseBetween(self, head, m, n):
        if m >= n:
            return head
        #Step 1#    
        ohead = dummy = ListNode(0)
        whead = wtail = head
        dummy.next = head
        for i in range(n-m):
            wtail = wtail.next
        #Step 2#  
        for i in range(m-1):
            ohead, whead, wtail = whead, whead.next, wtail.next
        #Step 3#  
        otail, wtail.next = wtail.next, None
        revhead, revtail = self.reverse(whead)
        #Step 4#  
        ohead.next, revtail.next = revhead, otail
        return dummy.next
            
    def reverse(self, head):
        pre, cur, tail = None, head, head
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre, tail
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值