Thursday, September 19, 2013

[Leetcode] Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5


Analysis:

1-->2-->3-->4-->5-->NULL
^p1       ^p2

NewNode->NULL
^p

After first iteration

1-->2-->3-->4-->5-->NULL
           ^p1          ^p2

NewNode-->2->1-->NULL
                            ^p

Use p2 to probe whether we still need to reverse the group.  If there is still more than k nodes left, iterate all node between p1 and p2 and insert it after p. Move p so that it always points to end of the new list.



ListNode *reverseKGroup(ListNode *head, int k) {
    ListNode* newNode = new ListNode(0);
    ListNode* p2 = head;
    ListNode* p1 = head;
    ListNode* p = newNode;
    while(1)
    {
        int i = 0;
        while(p2 != NULL && i < k)
        {
            i++;
            p2 = p2->next;
        }

        if (i != k)
            break;

        while(p1 != p2)
        {
            //insert p1 after p
            ListNode* next = p1->next;
            p1->next = p->next;
            p->next = p1;
            p1 = next;
        }

        //move p to end of the new list
        while(p != NULL &&p->next != NULL)
            p = p->next;
    }
    if (p != NULL)
        p->next = p1;
    head = newNode->next;
    delete newNode;
    return head;
} 

No comments:

Post a Comment