LeetCode 143. Reorder List
原题链接在这里:https://leetcode.com/problems/reorder-list/
题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→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}
.
题解:
找到中点,断开. 反转后半段,重新merge.
Time Complexity: O(n). Space O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public void reorderList(ListNode head) { 11 if(head == null || head.next == null){ 12 return; 13 } 14 15 ListNode mid = findMid(head); 16 ListNode midNext = mid.next; 17 mid.next = null; 18 ListNode reverseMidNext = reverse(midNext); 19 20 ListNode p = head; 21 ListNode q = reverseMidNext; 22 while(q!=null){ 23 ListNode qNext = q.next; 24 q.next = p.next; 25 p.next = q; 26 27 q = qNext; 28 p = p.next.next; 29 } 30 31 return; 32 } 33 34 private ListNode findMid(ListNode head){ 35 if(head == null || head.next == null){ 36 return head; 37 } 38 39 ListNode runner = head; 40 ListNode walker = head; 41 while(runner != null && runner.next != null && runner.next.next != null){ 42 walker = walker.next; 43 runner = runner.next.next; 44 } 45 46 return walker; 47 } 48 49 private ListNode reverse(ListNode head){ 50 if(head == null || head.next == null){ 51 return head; 52 } 53 54 ListNode tail = head; 55 ListNode cur = tail; 56 ListNode pre; 57 ListNode temp; 58 while(tail.next != null){ 59 pre = cur; 60 cur = tail.next; 61 temp = cur.next; 62 cur.next = pre; 63 tail.next = temp; 64 } 65 66 return cur; 67 } 68 }