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:
ListNode *ReverseList(ListNode * &from, ListNode * &to)
{
ListNode *ans = from;
ListNode *next = ans->next;
while (next != to)
{
ListNode *tmp = next->next;
next->next = ans;
ans = next;
next = tmp;
}
next->next = ans;
ans = next;
return ans;
}
ListNode *reverseBetween(ListNode *head, int m, int n)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL)
return NULL;
if (m == n)
{
return head;
}
ListNode *pParent1 = NULL;
ListNode *p1 = head;
m--;
while (m--)
{
pParent1 = p1;
p1 = p1->next;
}
n--;
ListNode *p2 = head;
ListNode *pNext = p2->next;
while (n--)
{
p2 = p2->next;
pNext = p2->next;
}
ListNode * pRev = ReverseList(p1, p2);
if (pParent1 == NULL)
{
head = pRev;
}
else
{
pParent1->next = pRev;
}
p1->next = pNext;
return head;
}