lintcode-medium-Reorder List

Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln

reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

 

Example

Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

Challenge

Can you do this in-place without altering the nodes' values?

 

/**
 * 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 || head.next.next == null)
            return;
        
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast != null && fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        
        ListNode head2 = slow.next;
        slow.next = null;
        
        head2 = reverse(head2);
        
        ListNode p1 = head;
        ListNode p2 = head2;
        ListNode p1_next = head.next;
        ListNode p2_next = head2.next;
        
        while(p1_next != null && p2_next != null){
            p1.next = p2;
            p2.next = p1_next;
            p1 = p1_next;
            p2 = p2_next;
            
            p1_next = p1_next.next;
            p2_next = p2_next.next;
        }
        p1.next = p2;
        p2.next = p1_next;
        
        return;
    }
    
    public ListNode reverse(ListNode head){
        if(head == null || head.next == null)
            return head;
        
        ListNode prev = head;
        ListNode curr = head.next;
        ListNode next = head.next.next;
        
        head.next = null;
        
        while(next != null){
            curr.next = prev;
            prev = curr;
            curr = next;
            next = next.next;
        }
        
        curr.next = prev;
        
        return curr;
    }
}

 

posted @ 2016-04-05 02:56  哥布林工程师  阅读(125)  评论(0编辑  收藏  举报