1. 程式人生 > >[leetcode] Reverse Linked List II

[leetcode] Reverse Linked List II

reverse 鏈表 csdn lac 這一 self. spa ive do it

題目內容

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->NULL, m = 2 and n = 4,

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

Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.

題目思路

這裏就要接著上一道題來繼續做了,上次說到單鏈表反轉的兩種方法,三指針法和頭插法。這一道題就需要用頭插法來做。具體可以參考這個博客:http://blog.csdn.net/feliciafay/article/details/6841115, 非常清晰。

先通過for循環找到需要反轉的鏈表的“head”

Python代碼

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

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        
""" if not head or not head.next: return head dummy=ListNode(-1) dummy.next=head h=dummy for i in range(m-1): h=h.next p=h.next for i in range(n-m): tmp=h.next h.next=p.next p.next
=p.next.next h.next.next=tmp return dummy.next

第二個for循環中的方法要記住,這是常規的單鏈表反轉方法(也可以用上述博客中的方法,值得學習)。

[leetcode] Reverse Linked List II