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 };
  • 相关阅读:
    echarts常用说明
    ionic4打包和ngix配置
    浏览器onbeforeunload
    vue中keepAlive的使用
    面试题
    git使用
    git常用命令
    ajax原理
    关于npm(一)
    React、Vue、Angular对比 ---- 新建及打包
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646748.html
Copyright © 2011-2022 走看看