zoukankan      html  css  js  c++  java
  • 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

     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         int reverseTimes = getLength(head) / k;
    14         ListNode dummy(0);
    15         dummy.next = head;
    16         ListNode* pre = &dummy;
    17         ListNode* cur = pre->next;
    18         while(reverseTimes--) {
    19             for(int i = 0; i < k - 1; i++) {
    20                 ListNode* move = cur->next;
    21                 cur->next = move->next;
    22                 move->next = pre->next;
    23                 pre->next = move;
    24             }
    25             pre = cur;
    26             cur = pre->next;
    27         }
    28         return dummy.next;
    29     }
    30     
    31     int getLength(ListNode *head) 
    32     {
    33         int length = 0;
    34         while(head) {
    35             length++;
    36             head = head->next;
    37         }
    38         return length;
    39     }
    40 };
  • 相关阅读:
    Hadoop出现 Wrong FS: hdfs://......错误的解决方法
    在Linux下安装JDK环境
    卸载Linux自带的JDK
    hadoop1.2.1伪分布模式安装教程
    spring配置bean的生命周期
    spring注入的四种方式
    python re模块search()与match()区别
    VB.NET操作Excel
    位运算
    Python简单源码解析
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646748.html
Copyright © 2011-2022 走看看