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

[leetcode]Reorder List

时间:2014-07-22 00:16:36      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   

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.

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

算法思路:

设置快慢指针将前半段与后半段分开,然后将后半段逆序,再逐个插入前半段,时间复杂度O(n),空间复杂度不定

思路1:

后半段的逆序,设置三指针,在原list基础上逆序,空间复杂度O(1)

后面还有一些题会用这个思路,这里就不实现了。

 

思路2:

后半段的逆序,借助栈,空间复杂度O(n),代码简单

代码如下:

 1 public class Solution {
 2     public void reorderList(ListNode head) {
 3         if(head == null || head.next == null) return ;
 4         ListNode hhead = new ListNode(0);
 5         hhead.next = head;
 6         ListNode fast = hhead;
 7         ListNode slow = hhead;
 8         while(fast != null && fast.next != null){
 9             fast = fast.next.next;
10             slow = slow.next;
11         }
12         ListNode stackPart = slow.next;
13         slow.next = null;
14         Stack<ListNode> stack = new Stack<ListNode>();
15         while(stackPart != null){
16             stack.push(stackPart);
17             stackPart = stackPart.next;
18         }
19         ListNode insert = head;
20         while(!stack.isEmpty()){
21             ListNode tem = stack.pop();
22             tem.next = insert.next;
23             insert.next = tem;
24             insert = tem.next;
25         }
26     }
27 }

 

[leetcode]Reorder List,布布扣,bubuko.com

[leetcode]Reorder List

标签:des   style   blog   http   color   io   

原文地址:http://www.cnblogs.com/huntfor/p/3858468.html

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