zoukankan      html  css  js  c++  java
  • 25. Reverse Nodes in k-Group

    25. 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.

    k is a positive integer and is less than or equal to the length of the linked 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  * function ListNode(val) {
     4  *     this.val = val;
     5  *     this.next = null;
     6  * }
     7  */
     8 /**
     9  * @param {ListNode} head
    10  * @param {number} k
    11  * @return {ListNode}
    12  */
    13 var reverseKGroup = function(head, k) {
    14     
    15     //上一题其实是k=2的情况
    16     
    17     if(k === 1){
    18         return head;
    19     }
    20     
    21     var temp = head;
    22     
    23     //举例来说,当k=2时,那我们需要判断head和head.next是不是null,因为这种表示最多1个节点,小于2。
    24     for(var i = 1;i < k;i++){
    25        
    26          if(temp === null || temp.next === null){
    27              return head;
    28          }
    29          
    30         temp = temp.next;
    31         
    32     }
    33     
    34     //关于满足k长度的节点链,我们用头插法实现反转
    35     //比如 1->2->3->4->5 k=4
    36     
    37     //(1) 0->2->1->3->4->5  pre指向val==1的node,cur指向val==2的node,next指向val==3的node
    38     //(2) 0->3->2->1->4->5
    39     //.....
    40     
    41     
    42     var newHead = new ListNode(0);
    43      newHead.next = head;
    44     
    45     var pre = newHead.next;
    46     var cur  = pre.next;
    47     var next = cur.next;
    48     
    49     for(var j = 1;j < k; j++){
    50         
    51         var tempHead = newHead.next;
    52         
    53         newHead.next = cur;
    54        
    55         cur.next = tempHead;
    56         
    57         
    58         
    59         pre.next = next;
    60         
    61         cur =  pre.next;
    62         
    63         next = cur !==null ? cur.next:null;
    64                
    65     }
    66     
    67     next = pre.next;
    68     pre.next = reverseKGroup(next,k);
    69     
    70     return newHead.next;
    71     
    72     
    73 };
  • 相关阅读:
    We need know.
    vue2.x加入fullpage全屏插件
    解决浏览器url带值访问报错URL编码encodeURI
    vue子组件修改父组件的值(子传父 )
    cli3多页面 webpack打包日志记录
    解决vue-cli npm run build之后vendor.js文件过大的方案
    vue使用UEditor富文本编辑器[实用]
    解决 cli3 自定义指令在ie11报错 SCRIPT1002: 语法错误
    cli3搭建项目配置代理跨域
    简易日期联动选择代码demo
  • 原文地址:https://www.cnblogs.com/huenchao/p/7685731.html
Copyright © 2011-2022 走看看