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 }
  • 相关阅读:
    leetcode16 3-Sum
    leetcode679:24Game
    leetcode621 贪心:任务安排
    SpringMVC中的Controller默认单例
    O(n)复杂度求没有出现的数字(leetcode448)
    SpringBoot获取ApplicationContext
    Largest Number(leetcode 179)
    使用免费ip代理进行投票
    Oracle分页
    Oracle JDBC配置
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8491336.html
Copyright © 2011-2022 走看看