LeetCode: Reverse Nodes in k-Group

来源:互联网 发布:域名服务器设置 编辑:程序博客网 时间:2024/06/05 10:43

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

思路:用一个指针记录已经转置的链表的尾节点。

从头节点开始,设置一个指针对其移动k个,将其断开,调用原地转置链表的代码。转置链表插入到已经转置好的链表的尾部。如果最后剩下不足k个,直接将剩余链表插入到尾部

代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    //原地转置链表函数    ListNode* reverseList(ListNode* head)    {        if(head == nullptr) return head;        ListNode *p = head;        ListNode *q = head->next;        head->next = nullptr;        while(q != nullptr)        {            ListNode *t = q->next;            q->next = p;            p = q;            q = t;        }        return p;    }    ListNode* reverseKGroup(ListNode* head, int k) {        //头节点为空或者分组为1可以直接返回        if(head == nullptr || k==1) return head;        //用于记录头节点和尾节点        ListNode* nhead = nullptr;        ListNode* ntail = nullptr;        //需要转置链表的头 p和尾 q        ListNode* p = head;        ListNode* q = p;        while(q!=nullptr)        {            //找到长度为k的链表            for(int step = 0; q != nullptr && step < (k-1); ++ step) q = q->next;            if(q == nullptr)            {                //如果没找到直接插入到尾部                if(nhead == nullptr) nhead =head;                else ntail->next = p;                break;            }            else            {                //找到了记录下一节点,并分割出一个链表进行转置                ListNode* t = q->next;                q->next = nullptr;                reverseList(p);                //将转置链表插入尾部,之前的头p成了尾,之前的尾q成为头。设置新的尾部为p                if(nhead == nullptr)                {                    ntail = p;                    nhead = q;                }                else                {                    ntail->next = q;                    ntail = p;                }                q = t;                p = t;            }        }        return nhead;    }};


0 0
原创粉丝点击