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:
Reverses the variant of the entire list, specifying the start and end points. Because m=1 changes the head node, it joins a dummy head node 1. Find the M-1 node in the original list start: The reversed part will be returned to the node after the change. Move from dummy to m-1 D->1->2->3->4->5->NULL | St 2. A partial list of links with a length of L = n-m+1 is reversed starting with P = Start->next. __________ | | | vd->1->2<-3<-4 5->null & nbsp | | | St p h0 &nbs P 3. Last reply __________ | | &NBSP | vd->1 2<-3<-4 5->null &NBSP ; |________|
Java code:20160601
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Reversebetween (ListNode head,intMintN) {//iterative//Base Case if(Head = =NULL|| Head.next = =NULL|| M < 1 | | M >=N) {returnHead; } ListNode Dummy=NewListNode (0); Dummy.next=Head; ListNode Pre=dummy; ListNode cur=Head; //move m-1 to the node before reverse start intCount = 1; while(Count <m) {Pre=cur; Cur=Cur.next; Count++; } ListNode beforereverse=Pre; ListNode Startreverse=cur; while(Count <=N) {ListNode next=Cur.next; Cur.next=Pre; Pre=cur; Cur=Next; Count++; } Beforereverse.next=Pre; Startreverse.next=cur; returnDummy.next; }}
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leetcode-reverse-linked-list-ii.html
Leetcode 92. Reverse Linked List II