[LeetCode] 143. Reorder List

Problem

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

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

Solution

class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) return;
        ListNode fast = head, slow = head.next, split = head;
        while (fast != null && fast.next != null) {
            split = slow; //to split slow to next half
            fast = fast.next.next;
            slow = slow.next;
        }
        //1 2 3 4 5
        //3, 3, 2 (fast, slow, split)
        //5, 4, 3 (fast, slow, split)
        
        //1 2 3 4
        //3, 3, 2
        split.next = null;
        ListNode l2 = reverse(slow);
        ListNode l1 = head;
        while (l2 != null) {
            ListNode n1 = l1.next;
            ListNode n2 = l2.next;
            l1.next = l2;
            l2.next = n1;
            l1 = n1;
            l2 = n2;
        }
        return;
    }
    private ListNode reverse(ListNode node) {
        ListNode pre = null;
        while (node != null) {
            ListNode next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        return pre;
    }
}

你可能感兴趣的:(java,linkedlist)