Topic:
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 the list. Test instructions: A list of two subscripts in a given list, reversing the list order between subscripts, remaining unchanged.
The operation of the reverse list is maintained with three pointers, noting that the last pointer may be a null pointer condition.
Consider reversing the start position and the end position of the next link, with the front pointer begin to reverse the beginning of the position of the previous pointer to facilitate operation, when the list is reversed from the beginning, the head pointer changes.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode (int x): Val (x), Next (NULL) {}
};
*
/class Solution {public
:
listnode *reversebetween (listnode *head, int m, int n) {
ListNode *begin , *P1,*P2,*P3;
int i;
Begin=head;
for (i=1;i<m-1;++i) begin=begin->next;
if (m!=1) p1=begin->next;
else P1=begin;
p2=p1->next;
if (p2) p3=p2->next;
for (i=0;i<n-m;++i) {
p2->next=p1;
P1=P2;
P2=P3;
if (p2) p3=p2->next;
}
if (m!=1) {
begin->next->next=p2;
begin->next=p1;
}
else {
begin->next=p2;
HEAD=P1;
}
return head;
}
;
Catalog