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

#include <iostream>


struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
   //至少长度是2
    void reverse(ListNode *& from,ListNode *& to){
        ListNode * p1 = from, *p2 = to;
        //递归出口
        if (from->next == to){
            to->next = from;
            from->next = NULL;
            from = p2;
            to = p1;
            return;
        }
        ListNode * p = from->next;
        reverse(p,to);
        to->next = from;
        from->next = NULL;
        //头和尾指针
        to = from;
        from = p;
        return;
    }
    ListNode *reverseKGroup(ListNode *head, int k) {
        /**
        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
        
        思路:先找到头K个结点,然后reverse头部,之后进行递归就ok
        */
        if (!head){
            return NULL;
        }
        if (k <= 1){
            return head;
        }
        ListNode * end = head;
        int m = 1;
        while(end->next && m < k){
            end = end->next;
            m++;
        }
        if (m < k){
            return head;
        }
        ListNode * end_next = end->next;
        //将头部的k个结点reverse
        reverse(head,end);
        //剩下的元素递归
        ListNode * q = reverseKGroup(end_next,k);
        //前后两块连接
        end->next = q;
        return head;
    }
};

using namespace std;
int main(int argc, char *argv[]) {
    int a[] = {1,2,3,4,5};
    ListNode node(0),*head = &node,*h = head;
    for(int i = 0; i < 5; i++){
        ListNode *p = new ListNode(a[i]);
        h = h->next = p;
    }
    Solution sol;
    ListNode * new_h = sol.reverseKGroup(head->next,1);
    for(ListNode * q = new_h; q; q = q->next){
        cout<<" "<< q->val;
    }
    cout << endl;
}

 

posted @ 2013-06-22 11:17  一只会思考的猪  阅读(202)  评论(0编辑  收藏  举报