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

    题目:

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

    You must do this in-place without altering the nodes' values.

    For example,
    Given {1,2,3,4}, reorder it to {1,4,2,3}.

    链接: http://leetcode.com/problems/reorder-list/

    6/12/2017

    参考别人的思路,自己写的代码。思路,找到中间点,后半部分反转,merge这两个半个链表

    注意:

    1. 找到后半部分起点之后,把前半部分最后一个元素next设为null

    2. 我的这个写法原始输入最中间的值会在second half的最后一个元素,所以second half length >= first half length,因此第16行要检测是否end.next是否为null

     1 public class Solution {
     2     public void reorderList(ListNode head) {
     3         if (head == null || head.next == null || head.next.next == null) {
     4             return;
     5         }
     6         ListNode mid = findMid(head);
     7         ListNode end = reverse(mid);
     8         ListNode next;
     9 
    10         ListNode nextF, nextS;
    11 
    12         while (head != null && end != null) {
    13             nextF = head.next;
    14             nextS = end.next;
    15             head.next = end;
    16             if (nextF != null) {
    17                 end.next = nextF;
    18             }
    19             head = nextF;
    20             end = nextS;
    21         }
    22         return;
    23     }
    24     private ListNode findMid(ListNode head) {
    25         ListNode slow = head, fast = head;
    26         ListNode prev = head;
    27         while (fast != null && fast.next != null) {
    28             fast = fast.next;
    29             fast = fast.next;
    30             prev = slow;
    31             slow = slow.next;
    32         }
    33         prev.next = null;
    34         return slow;
    35     }
    36     private ListNode reverse(ListNode head) {
    37         ListNode dummy = new ListNode(-1);
    38         ListNode next = head.next;
    39         while (head != null) {
    40             next = head.next;
    41             head.next = dummy.next;
    42             dummy.next = head;
    43             head = next;
    44         }
    45         return dummy.next;
    46     }
    47 }

    别人比较好的解法,不需要我之前那么多check

    https://discuss.leetcode.com/topic/13869/java-solution-with-3-steps

    更多讨论

    https://discuss.leetcode.com/category/151/reorder-list

  • 相关阅读:
    CF_402C Searching for Graph 乱搞题
    zoj Simple Equation 数论
    zoj 3757 Alice and Bob and Cue Sports 模拟
    uva_12535
    boj1267 Infinite’s Cave 树形dp + 背包
    CF_216_Div_2
    nxlog4go 简介
    log4go的一些改进设想
    nxlog4go 的配置驱动
    nxlog4go Log Levels and Pattern Layout
  • 原文地址:https://www.cnblogs.com/panini/p/6998154.html
Copyright © 2011-2022 走看看