Sunday, January 11, 2015

LeetCode 143: Reorder List

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if (head==null || head.next==null)
            return;
        
        // Step 1: Divide the list into two parts, e.g., L0->L1->L2 ===> L0->L1 and L2    
        ListNode slow = head;
        ListNode fast = head;
        
        while (slow.next!=null && fast.next.next!=null)
        {
            slow = slow.next;
            fast = fast.next.next;
            
            if (fast.next == null)
                break;
        }
        
        ListNode head1 = head;
        ListNode head2 = slow.next;
        slow.next = null; // Detach two lists
        
        // Step 2: Reverse the second part.
        ListNode helper = new ListNode(0);
        helper.next = head2;
        ListNode pre = helper;
        ListNode last = pre.next;
        ListNode cur = pre.next.next;
        
        while (cur != null)
        {
            last.next = cur.next;
            cur.next = pre.next;
            pre.next = cur;
            cur = last.next;
        }
        
        head2 = helper.next;
        
        // Step 3: Merge two parts.
        ListNode l1 = head1;
        ListNode l2 = head2;
        ListNode node;
       
        while (l2 != null)
        {
            node = l1.next;
            l1.next = l2;
            
            l1 = node;
            node = l2.next;
            
            l2.next = l1;
            l2 = node;
        }
    }
}

No comments:

Post a Comment