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.
/** Definition for singly-linked list. * Function ListNode (val) {* This.val = val; * This.next = null; *} /c11>*//** * @param {listnode} head * @param {number} m * @param {number} n * @return {ListNode}*/varReversebetween =function(Head, M, N) {varPrev =NULL; varnow =Head; varNext =Head.next; varIprev =NULL; varInext =NULL; varIhead =NULL; varItail =NULL; vars = 1; varNewhead =false; while(now) {if(S >= m && s <=N) {if(s = =m) {Itail=Now ; Iprev=prev; } if(s = =N) {ihead=Now ; Inext=Next; } Now.next=prev; Prev=Now ; now=Next; if(now) {Next=Now.next; } if(s = =N) {if(!Iprev) {Head=Ihead; } Else{Iprev.next=Ihead; } Itail.next=Inext; Break; } } Else{prev=Now ; now=Next; if(now) {Next=Now.next; }} s++; } returnhead;};
The code is ugly, with a lot of zero variables to save things, thinking and flip the whole list of the same problem. A brief idea is: with three pointers prev, now, next traverse the list, when the specified range starts the rollover operation, and by the way record the head and tail (Ihead, itail) and the corresponding joint part of the pointer (Iprev, Inext) so that the two parts will be connected after the final flip. It is particularly important to note that the head of the linked list may be changed.
[Leetcode] Reverse Linked List II