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

leetcode之Reorder List

时间:2015-04-16 17:26:51      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

这道题分三步:

1:首先将原来的链表拆分成两部分,用next和next.next分

2:将第二部分链表反转

3:将第一部分链表和第二部分反转了的链表merge

Takeaway Messages from This Problem

The three steps can be used to solve other problems of linked list. A little diagram may help better understand them.

Reverse List:

技术分享

Merge List:

技术分享

下面附上程序源码:

public void reorderList(ListNode head) {
        if(head == null || head.next==null)  
	    {  
	        return;  
	    }  
	    ListNode walker = head;  
	    ListNode runner = head;  
	    while(runner.next!=null && runner.next.next!=null)  
	    {  
	        walker = walker.next;  
	        runner = runner.next.next;  
	    }  
	    ListNode head1 = head;  
	    ListNode head2 = walker.next;  
	    walker.next = null;  
	    head2 = reverse(head2);  
	    while(head1!=null && head2!=null)  
	    {  
	        ListNode next = head2.next;  
	        head2.next = head1.next;  
	        head1.next = head2;  
	        head1 = head2.next;  
	        head2 = next;  
	    }  
    }
    private ListNode reverse(ListNode head)  
	{  
	    ListNode pre = null;  
	    ListNode cur = head;  
	    while(cur!=null)  
	    {  
	        ListNode next = cur.next;  
	        cur.next = pre;  
	        pre = cur;  
	        cur = next;  
	    }  
	    return pre;  
    }

  

leetcode之Reorder List

标签:

原文地址:http://www.cnblogs.com/gracyandjohn/p/4432402.html

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