zoukankan      html  css  js  c++  java
  • 【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 };
  • 相关阅读:
    python目录操作shutil
    python os.walk
    利用华为eNSP模拟器实现vlan之间的通信
    Python之道1-环境搭建与pycharm的配置django安装及MySQL数据库配置
    利用Excel做一些简单的数据分析
    Django中的枚举类型
    django使用model创建数据库表使用的字段
    ps 命令的十个简单用法
    goinception安装
    docker安装redis 指定配置文件且设置了密码
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4592818.html
Copyright © 2011-2022 走看看