/**
* 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 * dummy = new ListNode(-1);
dummy->next = head;
ListNode * left = dummy;
ListNode * right = dummy;
for(int i = 0; i < m - 1; ++i) {
left = left->next;
}
ListNode * prevTail = left;
left = left->next;
for(int i = 0; i < n; ++i) {
right = right->next;
}
ListNode * nextHead = right->next;
right->next = NULL;
ListNode * prev = nextHead;
ListNode * curr = left;
ListNode * next = NULL;
while(curr != NULL) {
ListNode * next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
prevTail->next = prev;
return dummy->next;
}
};
4/20/2014
Leetcode -- Reverse Linked List II
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment