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

01 ListNode *reverseKGroup(ListNode *head, int k) {
02     if(head==NULL)
03        return NULL;
04     ListNode* hd=head;
05     for(int i=0;i<k1;i++){
06         if(hd->next==NULL)
07            return head;
08         hd=hd->next;
09     }
10     ListNode* p=hd->next;
11     ListNode* tail=head;
12     ListNode* prv=p;
13     ListNode* cur=head;
14     ListNode* tmp=cur->next;
15     while(prv!=hd){
16        cur->next=prv;
17        prv=cur;
18        cur=tmp;
19        if(tmp==NULL)
20            break;
21        tmp=tmp->next;
22    }
23    tail->next=reverseKGroup(p,k);
24    return hd;
25 }
This entry was posted in Array and linked list, Recursive. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s