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 }
  • 相关阅读:
    hdu 刷题记录
    HDU step by step
    Codeforces Round #260 (Div. 2) B. Fedya and Maths
    Codeforces Round #260 (Div. 2) A. Laptops
    UVALive 6662 TheLastAnt
    UVALive 6661 Equal Sum Sets
    Codeforces Round #253 (Div. 2) A. Anton and Letters
    wikioi 3130 CYD刷题(背包)
    wikioi 1014 装箱问题(背包)
    [转]很特别的一个动态规划入门教程
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8491336.html
Copyright © 2011-2022 走看看