Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
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.
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) {}
* };
*/
typedef ListNode ln;
ln *reverse(ln *prev, ln *cur, ln *nxt, int n, ln **lastNode)
{
int cnt = 0;
ln *head = cur;
while(cur && cnt != n+1)
{
cnt++;
cur->next = prev;
prev = cur;
cur = nxt;
if (nxt)
nxt = nxt->next;
}
if(cur)
head->next = cur;
if(!cur)*lastNode = prev;
return prev;
}
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(!head || !head->next || (n-m<1))return head;
ln *prev = NULL, *cur=head, *nxt = head->next, *newHead = NULL;
int cnt = 1;
newHead = head;
while(cur && cnt!=m)
{
cnt++;
prev = cur;
cur = nxt;
if(nxt)
nxt = nxt->next;
}
ln *lastNode = NULL,*revHead = NULL;
revHead = reverse(NULL,cur,nxt, n-m, &lastNode);
if(prev)
prev->next = revHead;
else if(lastNode)
newHead = lastNode;
else newHead = revHead;
return newHead;
}
No comments:
Post a Comment