首页 > 其他 > 详细

[LeetCode 143] Reorder List

时间:2015-03-26 17:40:41      阅读:164      评论:0      收藏:0      [点我收藏+]

题目链接:reorder-list


/**
 * 
		Given a singly linked list L: L0→L1→…→Ln-1→Ln,
		reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
		
		You must do this in-place without altering the nodes' values.
		
		For example,
		Given {1,2,3,4}, reorder it to {1,4,2,3}.
 *
 */

public class ReorderList {
	
	public class ListNode {
		int val;
		ListNode next;
		ListNode(int x) {
			val = x;
			next = null;
		}
	}
	
//	13 / 13 test cases passed.
//	Status: Accepted
//	Runtime: 337 ms
//	Submitted: 23 minutes ago

	
    public void reorderList(ListNode head) {
    	ListNode midNode = head;
    	ListNode lastNode = head;
    	//找到链表的中点
    	while(lastNode.next != null && lastNode.next.next != null) {
    		midNode = midNode.next;
    		lastNode = lastNode.next.next;
    	}
    	
    	lastNode = midNode.next;
    	//断开链表
    	midNode.next = null;
    	
    	
    	//反转后半链表
    	midNode = reverseList(lastNode);
    	
    	//合并链表
    	ListNode cur = head;
    	while( midNode != null) {
    		ListNode node = cur.next;
    		cur.next = midNode;
    		midNode = midNode.next;
    		cur = cur.next;
    		cur.next = node;
    		cur = cur.next;
    	}
    }
    
    public ListNode reverseList(ListNode head) {
    	ListNode preHead = new ListNode(Integer.MAX_VALUE);
    	while(head != null) {
    		ListNode node = preHead.next;
    		preHead.next = head;
    		head = head.next;
    		preHead.next.next = node;
    	}
    	return preHead.next;
    }

    
	public static void main(String[] args) {
		System.out.println(Math.ceil(1.0 / 2.0));

	}

}


[LeetCode 143] Reorder List

原文:http://blog.csdn.net/ever223/article/details/44652121

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!