LeetCode Reverse Nodes in k-Group

来源:互联网 发布:快速域名网站备案 编辑:程序博客网 时间:2024/06/15 04:30

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:ListNode *reverseKGroup(ListNode *head, int k) {if (head == NULL || head->next == NULL || k <= 1)return head;ListNode *plast = head;ListNode *pslow = head;ListNode *pmid = head->next;ListNode *pfast = head->next;bool firstK = true;while (pfast != NULL) {//每次开始时,先检测下一组是否有k个节点,没有就结束循环。ListNode *ptemp = pslow;    for (int i = 0; i < k - 1; i++) {ptemp = ptemp->next; if (ptemp == NULL)break;}if (ptemp == NULL)   //结束整个大循环break;ptemp = pslow;       //临时保存每组k个节点的第一个节点//节点逆序,循环结束时,pslow 指向本组k个节点的最后一个(新链的第一个节点),// pmid 和 pfast 指向下一组的第一个节点for (int i = 0; i < k - 1; i++) {pfast = pmid->next;pmid->next = pslow;pslow = pmid;pmid = pfast;}//如果是第一组k个节点,则更新 head,否则让上一组逆序后的最后一个节点 链上本组逆序后的首节点if (firstK) {head = pslow;firstK = false;}else {plast->next = pslow;}//更新pslow,使其指向 下一组k个节点的第一个节点,让 pmid 和 pfast指向第二个节点 或 NULLpslow = pmid;            if (pfast != NULL) {pfast = pfast->next;pmid = pfast;}plast = ptemp;     // 更新plast, 使其指向本组 k个节点逆序后的最后一个节点}if (plast != pslow)    //将最后一组接上plast->next = pslow;return head;}};


0 0
原创粉丝点击