2016年9月12日星期一

[LintCode] #99 Reorder List

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: void
     */
    public void reorderList(ListNode head) {  
        // write your code here
        if (head == null || head.next == null) {
            return;
        }
        ListNode mid = findMiddle(head);
        ListNode head2 = reverse(mid.next);
        mid.next = null;
        merge(head, head2);
    }
    
    private ListNode findMiddle(ListNode head) {
        if (head == null && head.next == null) {
            return head;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    
    private static ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode tmp;
        while (cur != null) {
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
    
    private void merge(ListNode head1, ListNode head2) {
        ListNode tmp = new ListNode(0);
        boolean switchToHead2 = false;
        while (head1 != null && head2 != null) {
            if (!switchToHead2) {
                ListNode p = head1.next;
                tmp.next = head1;
                head1 = p;
            } else {
                ListNode p = head2.next;
                tmp.next = head2;
                head2 = p;
            }
            tmp = tmp.next;
            switchToHead2 = !switchToHead2;
        }
        if (head1 != null) {
            tmp.next = head1;
        }
        if (head2 != null) {
            tmp.next = head2;
        }
    }
}

没有评论:

发表评论