kiddy

Reverse Nodes in k-Group

leave a comment »

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

class Solution {
public:

    void revRec(ListNode *pre, int k){
        ListNode *end = pre;
        for(int i = 0; i < k; i++){
            if(end->next == NULL)    return;
            end = end->next;
        }
//when k==1, nextPre will be the end and do not go into the while
        ListNode *nextPre = end;
        
        while(pre->next != end){
            ListNode *start = pre->next;            
            if(nextPre == end) nextPre = start;
            pre->next = pre->next->next;
            start->next = end->next;
            end->next = start;
        }        
        revRec(nextPre, k);
    }


    ListNode *reverseKGroup(ListNode *head, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        //if(head == 0)   return NULL;
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode *pre = dummy;
        revRec(pre, k);
        ListNode *ret = dummy->next;
        delete dummy;
        return ret;
        
    }
};
class Solution {
public:

    ListNode* reverseOneGroup(ListNode* pre, ListNode* last) {
        ListNode* newLast = pre->next;
        while (pre->next != last) {
            ListNode* p1 = pre->next;
            pre->next = p1->next;
            p1->next = last->next;
            last->next = p1;
        }
        return newLast;
    }

    ListNode *reverseKGroup(ListNode *head, int k) {
        if (head == NULL)   return NULL;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy;
        while (true) {
            ListNode* last = pre;
            for (int i = 0; i < k; i++) {
                if (last->next) {
                    last = last->next;
                } else {
                    return dummy->next;
                }
            }
            pre = reverseOneGroup(pre, last);
        }
    }
};
Advertisements

Written by linzhongzl

April 24, 2013 at 11:16 am

Posted in Leetcode

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 )

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 )

w

Connecting to %s

%d bloggers like this: