Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:Given1->2->3->4->5->NULL, m = 2 and n = 4,
return1->4->3->2->5->NULL.
Note:Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ length of list.
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head==NULL||m == n)
return head;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* p = head;
ListNode* q = dummy;
for(int i=0;i<m-1;i++)
{
q = p;
p = p->next;
}
ListNode* pre = NULL;
ListNode* cur = p;
for(int i=m;i<=n;i++)
{
ListNode* pNext = cur->next;
cur->next = pre;
pre = cur;
cur = pNext;
}
q->next = pre;
p->next = cur;
return dummy->next;
}
};