zoukankan      html  css  js  c++  java
  • LeetCode 143 Reorder List

    注意: 

    merge的时候,cur1更新的位置不再是cur.next, 而是cur.next.next.

    思考方式: 

    (1) First, split the list into two sublists, using two pointers: fast and slow; Middle node is important!!
    (2) Second, use reverse method to reverse the second sublist.
    (3) Third, merge them together. Same as merge two sorted lists.

    NOTE:
    1. DON'T USE recursion for reverse method !!! recursion will spend more time than while() loop. Because recursion has to dive methods firstly and then go back to return result. But while() loop will only compute results in one-pass.

     1 public class Solution {
     2   public ListNode reorder(ListNode head) {
     3     // Write your solution here
     4       if (head == null || head.next == null) {
     5          return head; 
     6     }
     7     ListNode mid = findMid(head);
     8     ListNode head2 = reverse(mid.next);
     9     mid.next = null;
    10     ListNode res = merge(head, head2);
    11     return res;
    12   }
    13   private ListNode merge(ListNode head1, ListNode head2) {
    14     ListNode cur1 = head1, cur2 = head2;
    15     while (cur2 != null) {
    16         ListNode temp = cur2.next;
    17       cur2.next = cur1.next;
    18       cur1.next = cur2;
    19       cur2 = temp;
    20       cur1 = cur1.next.next;
    21     }
    22     return head1;
    23   }
    24   
    25   
    26   private ListNode reverse(ListNode head) {
    27       ListNode prev = null, cur = head;
    28     while (cur != null) {
    29       ListNode next = cur.next;
    30       cur.next = prev;
    31       prev = cur;
    32       cur = next;
    33     }
    34     return prev;
    35   }
    36   
    37   private ListNode findMid(ListNode head) {
    38       ListNode fast = head, slow = head;
    39     while (fast.next != null && fast.next.next != null) {
    40       fast = fast.next.next;
    41       slow = slow.next;
    42     }
    43     return slow;
    44   }
    45 }
  • 相关阅读:
    JS函数的定义与调用方法
    一次完整的浏览器请求流程
    【前端安全】JavaScript防http劫持与XSS
    深入理解display属性
    前端开发人员需要了解的CSS原理
    第 10 章 文件系统及实现
    第 9 章 虚拟内存管理
    第 8 章 内存管理策略
    第 7 章 死锁
    第 6 章 同步
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8491336.html
Copyright © 2011-2022 走看看