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

Problem link

Solution

  • dummy head, to avoid checking the head node
class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        head = dummy;
        int i;
        int start = 0;
        ListNode* next;
        ListNode* cur = head->next;
        ListNode* pre;
        while (cur){
            for (i=0; i<k && cur; i++, cur = cur->next); // check whether there are sufficient 
            if (i==k){
                pre = head->next;
                cur = pre->next;
                for (i=0; i<k-1; i++){
                    next = cur->next;
                    cur->next = pre;
                    pre = cur;
                    cur = next;
                }
                head->next->next = cur;
                next = head->next;
                head->next = pre;
                head = next;
                cur = head->next;
            }else{ // reaching the end of list
                head = dummy->next;
                delete dummy;
                return head;
            }
        }
        head = dummy->next;
        delete dummy;
        return head;
    }
};
Advertisements
Reverse Nodes in k-Group

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s