您的位置:首页 > Web前端 > Node.js

25. Reverse Nodes in k-Group

2016-05-16 21:55 543 查看
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


Subscribe to see which companies asked this question

分析:

此题意思是以k为单位,每次反转链表的k个值,再把这些反转的部分连接起来。

思路是:

按照反转的写法,按k为单位反转,记录单位链表(反转前)的首和尾,首接下一个单位链表的翻转后的首,尾接下一个的首,第一个注意翻转后的额首要保存,同时记得尾不需要被连接。

代码如下:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

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

 * };

 */

class Solution {

public:

    ListNode* reverseKGroup(ListNode* head, int k) {

        ListNode *pre,*result,*temp1,*temp2;

        pre=result=temp2=NULL;

        while(head==NULL||head->next==NULL||k==0||k==1) return head;

        ListNode* after=head;

        unsigned len=0;

        unsigned count=0;

        while(head)

        {

            head=head->next;

            len++;

        }

        head=after;

        int times=len/k;

        if(times==0) return head;

        bool in=true;

        after=NULL;

        while(head&×!=0)

        {

         

            times--;

            count=0;

            result=head;

            while(head&&count<k)

            {

                temp2=head->next;

                head->next=pre;

                pre=head;

                head=temp2;

                ++count;

            }

            

            if(in) {temp1=pre; in=false;}

            else  after->next=pre;

            after=result;

        }

        if(head) after->next=head;

        else after->next=NULL;

        return temp1;

        

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表