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.
The main idea is to give a single linked list, given a starting point and an end point, reversing the list between the starting point and the end point, requiring: in-situ inversion, one-time traversal.
Solution idea: Because already limited 1 ≤ m ≤ n ≤length of list, the set head node points to the first element, the working pointer goes first m step, uses the head interpolation method to reconstruct the data between M and N, Finally, the next pointer on the m position points to the position of the original n+1.
This time the code is a bit tangled, Java operations are not as good as C + + proficiency.
PublicListNode Reversebetween (ListNode head,intMintN) {if(Head = =NULL|| m = =N) {returnHead; } intCount = N-m; ListNode P=NewListNode (0); ListNode q; ListNode HEADP=NewListNode (0); ListNode Res=HEADP; P.next=Head; Headp.next=Head; while(--m > 0) {HEADP=Headp.next; } P=Headp.next; Q=P.next; ListNode Last=p; Headp.next=NULL; while(count-->= 0) {P.next=Headp.next; Headp.next=p; if(Q! =NULL) {p=Q; Q=Q.next; } Else{p=NULL; }} Last.next=p; /*while (res!=null) {System.out.println (res.val); Res=res.next; }*/ returnRes.next; }
Reverse Linked List Ii--leetcode