积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

==================

思路:

  没有什么坑,就是编码麻烦,

代码:

 

void help_reverseKGroup(ListNode *prev,ListNode *curr,int k){
        ListNode *p = prev->next;
        prev->next = curr->next;
        for(int i = 0;i<k;i++){
            ListNode *tmp = p->next;
            p->next = prev->next;
            prev->next = p;
            p = tmp;
        }
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(k<=1) return head;
        if(head==nullptr || head->next==nullptr)return head;
        ListNode dummy(-1);
        dummy.next = head;
        ListNode *curr,*prev;
        curr = head;
        prev = &dummy;

        while(curr){
            int i = 1;
            for(;i<k;i++){
                if(curr->next)  curr = curr->next;
                else break;
            }
            if(i!=k) break;
            //showList(dummy.next);cout<<"k1"<<endl;

            help_reverseKGroup(prev,curr,k);

            //showList(dummy.next);cout<<"k2"<<endl;
            for(i = 0;i<k;i++){
                prev = curr;
                curr = curr->next;
            }
            //showList(head);cout<<"k3"<<endl;
        }///while
        return dummy.next;
    }

 

posted on 2016-06-22 16:22  x7b5g  阅读(146)  评论(0编辑  收藏  举报