Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

这题不难,算是Revese Linked List 的升级版,加上了边缘处理。

具体解题思路为: 先找到第m-1个结点,反转m到n部分的结点,连接m和n+1,连接n和m-1.示意图如下(参考自Yanbing Shi博客):

1. 找到原链表中第m-1个节点start:反转后的部分将接回改节点后。
从dummy开始移动m-1步
 
D->1->2->3->4->5->NULL
       |
      st
 
2. 将从p = start->next开始,长度为L = n-m+1的部分链表反转。
            __________
            |                  |
            |                 V
D->1->2<-3<-4    5->NULL             
       |     |           | 
      st    p          h0         
 
3. 最后接回
 
            __________
            |                  |
            |                 V
D->1   2<-3<-4    5->NULL             
       |________|        
一遍扫,时间复杂度O(n),空间复杂度O(1),代码如下:
class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if m==n:
            return head 
        dummy = ListNode(-1)
        dummy.next = head 
        head = dummy
        
        for i in range(m-1):   #步数需要想清楚
            head = head.next
            
        prev = head.next
        cur = prev.next
        
        for i in range(n-m):   #步数需要想清楚
            next = cur.next
            cur.next = prev
            prev = cur 
            cur = next 
        head.next.next = cur #此时head.next依然指向最开始反转的节点.一个节点不可以有两个next,但是两个节点的next可以同时指向同一个节点.
        head.next = prev 
return dummy.next
原文地址:https://www.cnblogs.com/sherylwang/p/5436803.html