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.
Test Instructions: reverses the linked list, reversing the linked list at the specified position.
idea: refer to Here, the main is to find to reverse the beginning of the linked list of the junction of the reverse, and then one by one reversal, and finally and its side of the part to connect.
Code:
PublicListNode Reversebetween (ListNode head,intMintN) {if(head==NULL)return NULL; ListNode Q=NULL; ListNode P=Head; for(inti=0;i<m-1;i++) {Q=p; P=P.next; } ListNode End=p; ListNode Ppre=p; P=P.next; for(inti=m+1;i<=n;i++) {ListNode Pnext=P.next; P.next=Ppre; Ppre=p; P=Pnext; } End.next=p; if(q!=NULL) Q.next=Ppre; ElseHead=Ppre; returnHead; }
Leetcode (Reverse): Linked List II