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 };
  • 相关阅读:
    在VC6.0中虚函数的实现原理
    札记Microsoft基本类库应用程序框架
    typedef用法剖析
    申请成功记录记录
    vc++6.0环境中swap函数
    ubuntu12.04 安装JDK7
    N皇后问题的位运算求解——目前最快的方法
    Linux常用命令小结
    Ubuntu添加自己的桌面快捷方式
    C++静态成员函数小结(转)
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4592818.html
Copyright © 2011-2022 走看看