zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Reverse Nodes in k-Group

    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

    https://leetcode.com/problems/reverse-nodes-in-k-group/


    指针好费劲。

     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     var res = new ListNode(-1);
    15     var resTail = res;
    16     var h = null, t = null;
    17     var count = 0;
    18     while(head){
    19         if(!h && !t){
    20             h = t = head;
    21         }else{
    22             t = t.next; 
    23         }  
    24         head = head.next;  
    25         count++;   
    26 
    27         if(count === k){
    28             reverse(h, t);
    29             resTail.next = t;
    30             resTail = h;
    31             head = h.next;
    32             h = t = null;
    33             count = 0;
    34         }
    35     }
    36     if(count !== 0){
    37         resTail.next = h;
    38     }
    39     return res.next;
    40 
    41     function reverse(start, end){
    42         var head = new ListNode(-1);
    43         head.next = start;
    44         start = start.next;
    45         var tail = head.next;
    46         var count = 1;
    47         while(count != k){
    48             var tmp = start.next;
    49             start.next = head.next;
    50             head.next = start;
    51             start = tmp;
    52             tail.next = tmp;
    53             count ++;
    54         }
    55     }
    56 };

     

  • 相关阅读:
    洛谷
    洛谷
    洛谷
    洛谷
    模板
    .
    洛谷
    洛谷
    洛谷
    poj 2955"Brackets"(区间DP)
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4539713.html
Copyright © 2011-2022 走看看