Friday, April 11, 2014

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
Solution:
 Reverse node one by one : 1->2->3  to 2->1->3
Use a dummy to check whether there K  nodes left
Use 3 pointers: pre, first, second: pre and first is always the same, the only change is in second
Code:
    ListNode *reverseKGroup(ListNode *head, int k) {
    if (!head || !head->next)
        return head;

    ListNode *Head = new ListNode(-1);
    Head->next = head;

    ListNode *pre = Head;
    ListNode *dummy = head;
    ListNode *first = head;
    ListNode *second, *tmp;


     int tt =1, cnt;
    dummy = head;
    while (dummy->next && tt
    {
        dummy = dummy->next;
        tt++;
    }
    // check whether the left is K length enough

    while( tt ==k)
    {
        cnt = k;
        while(cnt-1>0)
        {
            second  = first->next;
            tmp = second->next;
             second->next = pre->next;
            pre->next=second;
            first->next = tmp;
            cnt--;
        }
        pre = first;
        first = first->next;

        tt =1;
        dummy = first;
        if (dummy)
        {
            while (dummy->next && tt
            {
                dummy = dummy->next;
                tt++;
            }
        }
                else
            break;
     }

     head = Head->next;
     delete Head;
     return head;
    }

No comments:

Post a Comment