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

    小细节太多了,需要注意!!!

     1 public ListNode reverseKGroup(ListNode head, int k) {
     2     if (head == null || head.next == null) {
     3         return head;
     4     }
     5     ListNode dummy = new ListNode(0);
     6     dummy.next = head;
     7     ListNode cur = dummy;
     8     
     9     while (cur != null) {
    10         cur = reverseK(cur, k);
    11     }
    12     return dummy.next;
    13 }
    14 
    15 // 1  ->  2  ->  3  ->  4  ->  5 ->  6  k = 2
    16 //head         node
    17 //             cur    next
    18 // 2 -> 1   ->  3  ->  4  
    19 private ListNode reverseK(ListNode head, int k) {
    20 ListNode tail = head;
    21 ListNode prev = head;
    22 ListNode n1 = head.next; //翻转list中的第一个元素。
    23 for (int i = 0; i < k; i++) {
    24 tail = tail.next;
    25 //这里要判断剩余部分不够k的数的时候。直接返回null,不进行任何操作。
    26 if (tail == null) {
    27 return null;
    28 }
    29 }
    30 
    31 ListNode next = tail.next;
    32     //           1 ->  2  ->  3     |    ->  4  ->  5
    33     //   head  first        tail            next 
    34 
    35 ListNode newHead = reverse(head.next, tail);
    36     //    head      3 -> 2  ->  1 ->   |   4  ->  5  -> null
    37     //            newH        first       next
    38 
    39 prev.next = newHead;
    40 n1.next = next;
    41 //不要返回next。 把n1当作下一次调用的dummy node, 所以每次返回的都是dummy node
    42 return n1;
    43 }
    44 
    45 private ListNode reverse(ListNode head, ListNode tail) {
    46     if (head == tail) {
    47         return head;
    48     }
    49     ListNode prev = null, cur = head;
    50     while (cur != tail) {
    51         ListNode next = cur.next;
    52         cur.next = prev;
    53         prev = cur;
    54         cur = next;
    55     }
    56     
    57     if (cur == null) {
    58         return prev;
    59     }
    60     cur.next = prev;
    61     return cur;
    62 }
  • 相关阅读:
    mongodb删除指定字段
    nodejs地理坐标转换
    浅谈对腾讯云微信小程序解决方案服务端的理解(主要针对信道服务)
    利用Django进行微信支付接口的开发
    SpringBoot常用注解
    构建一个敏感词字典树
    Java异常统一处理
    [一天一个小知识]instanceof
    [总结]实现表格中对checkbox的操作
    小程序的数据绑定
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8492103.html
Copyright © 2011-2022 走看看