Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created August 11, 2014 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/4926def3c67d8f2e4010 to your computer and use it in GitHub Desktop.
Save xiren-wang/4926def3c67d8f2e4010 to your computer and use it in GitHub Desktop.
Reverse Linked List II. Reverse a linked list from position m to n. Do it in-place and in one-pass. 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) {
ListNode * newHead = NULL;
ListNode * newTail = NULL;
ListNode * tail = head, *PrevOfNewList = NULL;
// scan to the end, reverse M to N
// inserting newEle in front of newHead, update newHead
// newTail-> tail'sNext
//Note: if m == 1, then must return newHead
// else, return oldHead (reversed LL as a section inside)
int nodeCnt = 0;
while(tail) {
nodeCnt ++;
if (nodeCnt == m-1)
PrevOfNewList = tail;
if (nodeCnt < m ) {
tail = tail->next;
continue;
}
if (nodeCnt > n)
break;
//now reverse the list
ListNode *tailNext = tail->next;
if (!newHead) {
newHead = tail;
newTail = newHead;
}
else { // tail --> newHead, then update newHead
tail->next = newHead;
newHead = tail;
}
newTail->next = tailNext;
tail = tailNext;
}
if (PrevOfNewList)
PrevOfNewList->next = newHead;
if (m == 1)
return newHead;
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment