zoukankan      html  css  js  c++  java
  • LeetCode OJ:Reverse Nodes in k-Group(K个K个的分割节点)

    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个的节点反转,即可,用到的记录节点可能比较多,写的比较乱,代码如下所示:

     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(k == 1) return head;
    13         if(!head || !head->next)
    14             return head;
    15         int len = 0;
    16         ListNode * p1 = head;
    17         while(p1){
    18             p1 = p1->next;
    19             len++;
    20         }
    21         //如果k比总长度还要长,那么直接返回即可
    22         if(len < k) return head;
    23         ListNode * prev = NULL;
    24         ListNode * curr = head;
    25         ListNode * tmpNode = NULL;
    26         ListNode * ret = new ListNode(-1);
    27         ListNode * helper = curr;
    28         ListNode * helperPre = NULL;
    29         while(len >= k){
    30             for(int i = 0; i < k; i++){//区域反转
    31                    tmpNode = curr->next;
    32                    curr->next = prev;
    33                    prev = curr;
    34                    curr = tmpNode;
    35             }
    36             if(!ret->next){//第一次手下记下的是首节点的位置
    37                 ret->next = prev;
    38             }else{
    39                 helperPre->next = prev;//以后将上一部分的尾节点连接到此部分的首节点上面
    40             }
    41             helper->next = curr;
    42             prev = helper;
    43             helper = curr;
    44             helperPre = prev;
    45             len -= k;
    46         }
    47         helperPre->next = curr;//将上次的尾节点域剩下的节点连接起来
    48         return ret->next;
    49     }
    50 };
  • 相关阅读:
    Linux .bashrc文件设置快速访问快捷键
    Fiddler如何添加ServerIP显示
    软件测试工程师常用工具汇总
    [ASP.NET Core开发实战]基础篇04 主机
    《数据结构与算法之美》24——堆的应用
    [ASP.NET Core开发实战]基础篇03 中间件
    《数据结构与算法之美》23——堆和堆排序
    [ASP.NET Core开发实战]基础篇02 依赖注入
    [ASP.NET Core开发实战]基础篇01 Startup
    [ASP.NET Core开发实战]开篇词
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5008427.html
Copyright © 2011-2022 走看看