143. Reorder List

# Medium

Key idea: find middle + reverse latter part + merge

length of list is even
length of list is odd

Python example: 注意快慢指针的终止条件,慢指针指向的位置,要把两个list分开

class Solution {
    public void reorderList(ListNode head) {
        // edge case
        if(head == null || head.next == null)
            return;
        
        // slow and fast pointer to find the middle point pre
        ListNode slow = head, fast = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // reverse the second part from pre
        ListNode pre = null, curr = slow;
        while(curr != null) {
            ListNode tempNext = curr.next;
            curr.next = pre;
            
            pre = curr;
            curr = tempNext;
        } // pre is the new head of second part
        
        // combine them
        ListNode head1 = head, head2 = pre;
        while(head2.next != null) {
            ListNode next1 = head1.next;
            ListNode next2 = head2.next;
            
            head1.next = head2;
            head2.next = next1;
            
            head1 = next1;
            head2 = next2;
        }
    }
}

T = O(N/2 + N/2) = O(N), S = O(1)

Last updated

Was this helpful?