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 };
  • 相关阅读:
    常用的 写代码 的 指令
    boos
    超级搬运工
    那些年,我读过的书籍(读完一本就在此处更新),立贴。
    ExtJs combobox模糊匹配
    整理了一下eclipse 快捷键注释的一份文档
    中国省份按照拼音排序出现的问题以及临时解决方案
    JetBrains WebStorm 安装破解问题
    ExtJs Grid 删除,编辑,查看详细等超链接处理
    ExtJs Panel 滚动条设置
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4592818.html
Copyright © 2011-2022 走看看