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 }
  • 相关阅读:
    android 解密工具
    android打包需要的图标
    Mac 创建软链接
    历届试题 Excel地址
    算法训练 字串统计
    最长回文子串
    算法提高 P1001【大数乘法】
    算法提高 拿糖果【埃氏筛 动态规划】
    算法训练 未名湖边的烦恼
    算法提高 合并石子【动态规划】
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8491336.html
Copyright © 2011-2022 走看看