Friday, April 24, 2015

[LeetCode] Reverse Linked List II

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->NULLm = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given mn 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 ret(0);
        ret.next = head;
        ListNode *prev = &ret;
        ListNode *mNode, *nNode, *mPrev;
        int i=1;
        while(head)
        {
            if(i == m)
            {
                mPrev = prev; 
                mNode = head;
            }
            if(i>=m && i<=n)
            {
                ListNode *tmp = head->next;
                head->next = nNode;
                nNode = head;
                head = tmp;
            }
            else
            {
                prev = head;
                head = head->next;
            }
            if(i==n)
            {
                mPrev->next = nNode;
                mNode->next = head;
                break;
            }
            i++;
        }
        return ret.next;
    }
};