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 }
  • 相关阅读:
    Python 爬虫一 简介
    linux 基础笔记本
    Celery 分布式任务队列快速入门
    Git & Github
    Python 设计模式
    Python 数据结构
    Python 基础算法
    js2wordcloud 词云包的使用
    lambda 3
    sql server 远程
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8491336.html
Copyright © 2011-2022 走看看