https://leetcode.com/problems/reverse-linked-list-ii/
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->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.
Title: Reverse the nodes of the specified position segment. (referring to the inverse method of the reverse function of reverse Nodes in K-group)
1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8 #@param {ListNode} head9 #@param {integer} mTen #@param {integer} n One #@return {ListNode} A defReversebetween (self, head, M, N): - ifHead==noneorhead.next==None: - returnHead thedummy=listnode (0) -dummy.next=Head -head1=Dummy - forIinchRange (m-1): +Head1=head1.next#Head1 placed in the previous item of the starting M -P=head1.next#p placed at start item m + forIinchRange (N-M):#Loop n-m The following operations, all subsequent items of item 1th are sequentially pre-placed, leading to reverse order ATmp=p.next; P.next=tmp.next#Remove the 2nd item and keep the back connection atTmp.next=head1.next; Head1.next=tmp#Place the 2nd item at the beginning of the row sequence - returnDummy.next#2,3,4,5--3,2,4,5--4,3,2,5--5,4,3,2, the number of the back of 2 is pre-placed, and it takes n-m times to do this
Reverse Linked List II