Leetcode 143. 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}
.
Analysis:
- Break list in the middle to two lists (use fast & slow pointers)
- Reverse the order of the second list
- Merge two list back together
Java code:
20160601
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public void reorderList(ListNode head) { //1.find the middle node in the list and split it into two small list //2. reverse the second list //3. merge two halves into one long list //base case if(head == null || head.next == null) { return; } ListNode mid = findMiddle(head); ListNode one = head; ListNode two = mid.next; mid.next = null; two = reverse(two); merge(one, two); } private ListNode findMiddle(ListNode head) { if(head == null || head.next == null) { return head; } ListNode slow = head, fast = head; while(fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } private ListNode reverse(ListNode head) { //iteration if(head == null || head.next == null) { return head; } ListNode pre = null; ListNode cur = head; while(cur != null) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } private void merge(ListNode one, ListNode two) { while(two != null) { ListNode next1 = one.next; ListNode next2 = two.next; one.next = two; two.next = next1; one = next1; two = next2; } } }