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.
Ideas:
The general list of inverse problems are from the front to the back one by one, this is no exception. Bfore points to the previous node of M (if m=1,before=null). Start is the first M node, which is the node that starts the reverse. End and after nodes are gradually changing backwards, and end is the node in front of after, which points the after next to end. The relationship of the two nodes depends on p to transition.
Exercises
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*reversebetween (ListNode *head,intMintN) {if(m==N)returnHead; ListNode*p =Head; ListNode*before, *start, *end, *After ; Before=start=end=after=NULL; for(intI=1; i<m;i++) {before=p; P= p->Next; } Start=end=p; P= p->Next; for(inti=m;i<n;i++) { after= p->Next; P->next =end; End=p; P=After ; } Start->next =After ; if(before!=NULL) before->next =end; ElseHead=end; returnHead; }};
View Code
[Leetcode] Reverse Linked List II