1. 程式人生 > >143. Reorder List

143. Reorder List

com example 參考 listnode http slow list prev lis

題目:

Given a singly linked list L: L0→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