[LeetCode] Reverse Linked List II @ Python [提供自创的示意图 Figure illustration]

原题地址:https://oj.leetcode.com/problems/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.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

解题思路:翻转链表的题目。请用积木化思维(Building block): 

这里必须的积木:链表翻转操作:

curr.next, prev, curr = prev, curr, curr.next

 

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

class Solution:
    # @param head, a ListNode
    # @param m, an integer
    # @param n, an integer
    # @return a ListNode
    def reverseBetween(self, head, m, n):
        dummy, diff = ListNode(0), n - m
        dummy.next = head
        prev, curr = dummy, dummy.next
        while m > 1:
            prev, curr = curr, curr.next
            m -= 1
        last_unswapped, first_swapped = prev, curr
        while curr and diff >= 0:
            curr.next, prev, curr = prev, curr, curr.next
            diff -= 1
        last_unswapped.next, first_swapped.next = prev, curr
        return dummy.next
        # Here is an exmple
        # 1 --> 2 --> 3 --> 4 --> 5
        #       
        # Before first while-loop
        #      0 --> 1 --> 2 --> 3 --> 4 --> 5
        #      prev  curr
        # After first while-loop 
        #      0 --> 1 --> 2 --> 3 --> 4 --> 5 
        #            prev curr 
        #  last_unswapped, first_swapped = prev, curr
        # The following is the details for 2nd while-loop
        # diff=2 #   1 <-- 2     3 --> 4 --> 5
        #                 prev  curr
        # diff=1 #   1 <-- 2 <-- 3     4 --> 5
        #                       prev  curr
        # diff=0 #   1 <-- 2 <-- 3 <-- 4     5
        #                             prev  curr
        # last_unswapped.next = prev
        # first_swapped.next  = curr
        # After impletenting the above two lines, we get:
        #         first_swapped.next = curr
        #          __________________  
        #          ^                 |      
        #          |                 V 
        # 1        2 <-- 3 <-- 4     5
        # |                    ^
        # V ___________________| 
        # last_unswapped.next=prev    
        # Reverse partial Linked List
        # Refer Figure1: //images0.cnblogs.com/i/546654/201404/072244468407048.jpg
        # Refer: http://www.cnblogs.com/4everlove/p/3651002.html
        # Refer: http://stackoverflow.com/questions/21529359/reversing-a-linked-list-in-python

 

posted on 2014-09-14 23:04  AIDasr  阅读(909)  评论(0编辑  收藏  举报

导航