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.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
assert(m<=n);
int count = 1;
ListNode* vHead = new ListNode(-1);
vHead->next = head;
ListNode* last = vHead;
ListNode* first = head;
for(int i=1;i<m;i++)
{
last = last->next;
first = first->next;
}
ListNode* pre = last->next;
ListNode* current = last->next->next;
ListNode* temp;
for(int i=m;i<n;i++)
{
temp = current->next;
current->next = pre;
pre = current;
current = temp;
}
last->next = pre; //Think Through!
first->next = current;
return vHead->next;
}
};