码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Reorder List

时间:2016-04-05 07:05:10      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

lintcode-medium-Reorder List

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5353624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!