2015年4月28日星期二

Reorder List leetcode

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…
You must do this in-place without altering the nodes' values.

Example
For example,
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.
第一步,将链表分为两部分。时间O(n)
第二步,将第二部分链表逆序。时间O(n)
第三步,将链表重新组合。时间O(n)
总体时间O(n) 空间O(1)

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: void
     */
    public void reorderList(ListNode head) {  
        if (head == null || head.next == null){
            return ;
        }
        ListNode mid = findmid(head);
        ListNode tail = reverse(mid.next);
        mid.next = null;
        merge(head, tail);
    }
    private ListNode findmid(ListNode head){
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    private ListNode reverse(ListNode head){
        ListNode prev = null;
        while (head != null){
            ListNode tem = head.next;
            head.next = prev;
            prev = head;
            head = tem;
        }
        return prev;
    }
    private void merge(ListNode head, ListNode tail){
        ListNode dummy = new ListNode(0);
        while (head != null && tail != null){
            dummy.next = head;
            head = head.next;
            dummy = dummy.next;
            dummy.next = tail;
            tail = tail.next;
            dummy = dummy.next;
        }
        if (head != null){
            dummy.next = head;
        } else {
            dummy.next = tail;
        }
    }
}

没有评论:

发表评论