首页 > 代码库 > 143. Reorder List

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

143. Reorder List