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 };
  • 相关阅读:
    三调数据库标注插件
    ionic ios 打包发布流程
    ionic ios 打包 真机测试常见问题
    使用Jquery Viewer 展示图片信息
    微信支付退款证书服务器配置
    帝国CMS站点迁移
    solr 服务器搭建(Linux版)
    ionic ios 打包
    Solr 同义词搜索
    ionic 环境搭建
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5008427.html
Copyright © 2011-2022 走看看