Original title address: https://oj.leetcode.com/problems/reverse-linked-list-ii/
Test instructions
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.
Problem-solving ideas: Flipping the list of topics. Please use the brick Thinking (Building block):
Here are the necessary building blocks: List flipping operations:
Current.next, prev, current = prev, current, Current.next
Code:
#Definition for singly-linked list.#class ListNode:#def __init__ (self, x):#self.val = x#Self.next = NoneclassSolution:#@param head, a listnode #@param m, an integer #@param n, an integer #@return a ListNode defReversebetween (self, head, M, N): diff, Dummy= N-m, ListNode (0) Dummy.next=Head prev, current=Dummy, Dummy.next whileCurrent andM >1: prev, current=Current , Current.next m-= 1last_swapped, first_swapped=Prev, current whileCurrent andDiff >=0:current.next, prev, current=prev, Current, Current.next diff-= 1Last_swapped.next, First_swapped.next=Prev, currentreturnDummy.next#Reverse partial Linked List #Refer figure1:http://images.cnitblog.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 #1 --2--3--4--5 # #First_swapped.next = current # __________________ # ^ | # | V #1 2 <--3 <--4 5 # | ^ #V ________________| #Last_unswapped.next=prev
[Leetcode] Reverse Linked List II @ Python