[LintCode] Reorder List

Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-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.

 
SOLUTION:
怎么才能满足这样的排序呢?很简单,先二分,把它分成两个链表,再翻转后面的链表,再合并两个链表。单个功能的实现,前面都有了就不赘述了。
 
代码:
/**
 * 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) {  
        if (head == null || head.next == null){
            return;
        }
        ListNode mid = findMid(head);
        ListNode node = mid.next;
        mid.next = null;
        node = reverse(node);
        head = merge(head, node);
    }
    private ListNode findMid(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    private ListNode reverse(ListNode head){
        if (head == null){
            return head;
        }
        ListNode prev = null;
        while (head != null){//错误的地方
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
    private ListNode merge(ListNode l1, ListNode l2){
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while (l1 != null && l2 != null){
            head.next = l1;
            head = l1;
            l1 = l1.next;
            head.next = l2;
            head = l2;
            l2 = l2.next;
        }
        if (l1 != null){
            head.next = l1;
        }
        if (l2 != null){
            head.next = l2;
        }
        return dummy.next;
    }
}
View Code

 

posted @ 2015-11-17 11:29  Tri_tri_tri  阅读(177)  评论(0)    收藏  举报