• 【Leetcode】【Hard】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

    解题:

    先写一个函数,输入为待反转的子链表首结点和k,功能是反转子链表前K个结点,剩余结点不变;如果不够K个结点,则保持原链表。

    之后循环调用此函数。

    代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* reverseKGroup(ListNode* head, int k) {
    12         if (head == NULL || head->next == NULL || k == 1)
    13             return head;
    14         ListNode* newhead = new ListNode(0);
    15         ListNode* newlist = newhead;
    16         ListNode* curNode = head;
    17         while (curNode != NULL) {
    18             newlist->next = reverseListKNodes(curNode, k);
    19             // After "reverseListKNodes" func, "curNode" will be the end of reversed sublist
    20             newlist = curNode;
    21             curNode = curNode->next;
    22         }
    23         
    24         head = newhead->next;
    25         delete newhead;
    26         return head;
    27     }
    28     
    29     ListNode* reverseListKNodes(ListNode* sub_head, int k) {
    30         if (sub_head == NULL || sub_head->next == NULL)
    31             return sub_head;
    32             
    33         ListNode* newhead = NULL;
    34         ListNode* nodesleft = sub_head;
    35         ListNode* curNode = NULL;
    36         
    37         for (int i = 0; i < k; ++i) {
    38             if (nodesleft == NULL)
    39                 return reverseListKNodes(newhead, i);
    40             curNode = nodesleft;
    41             nodesleft = nodesleft->next;
    42             curNode->next = newhead;
    43             newhead = curNode;
    44         }
    45         
    46         sub_head->next = nodesleft;
    47         return newhead;
    48     }
    49 };
  • 相关阅读:
    软件工程课程总结
    团队-象棋游戏-团队一阶段互评
    课后作业-结对编程项目总结
    团队-象棋游戏-模块测试过程
    团队编程项目作业3-模块开发过程
    结对-结对编项目作业名称-最终程序
    2017-10-30 课后作业-阅读任务-阅读提问
    阅读任务-阅读提问
    2017-10-30 课后作业-阅读任务-阅读笔记-2
    2017-10-06-构建之法:现代软件工程-阅读笔记
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4592818.html
Copyright © 2020-2023  润新知