[leetcode]Reorder List

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 }

 

第二遍:

想到了用栈,但是也想到了第一遍肯定用的栈,因此这一次记录了每个Node的下标,酱紫,就可以看着题中给的下标动手了。

代码如下:

 

 1 public class Solution {
 2     public void reorderList(ListNode head) {
 3         if(head == null || head.next == null) return;
 4         Map<Integer,ListNode> map = new HashMap<Integer,ListNode>();
 5         ListNode pre = head;
 6         int index = 0;
 7         while(pre != null){
 8             map.put(index,pre);
 9             index++;
10             pre = pre.next;
11         }
12         for(int i = 0; i < (index - 1)>>1; i++){
13             ListNode small = map.get(i);
14             ListNode big = map.get(index - 1- i);
15                big.next = small.next;
16                small.next = big;
17         }
18         map.get(index>>1).next = null;
19         return;
20     }
21 }
View Code

 

posted on 2014-07-21 15:13  喵星人与汪星人  阅读(277)  评论(0编辑  收藏  举报