您的位置:首页 > 其它

[leetcode]Reorder List

2014-07-21 15:13 232 查看

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


算法思路:

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

思路1:

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

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

思路2:

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

代码如下:

public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return ;
ListNode hhead = new ListNode(0);
hhead.next = head;
ListNode fast = hhead;
ListNode slow = hhead;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode stackPart = slow.next;
slow.next = null;
Stack<ListNode> stack = new Stack<ListNode>();
while(stackPart != null){
stack.push(stackPart);
stackPart = stackPart.next;
}
ListNode insert = head;
while(!stack.isEmpty()){
ListNode tem = stack.pop();
tem.next = insert.next;
insert.next = tem;
insert = tem.next;
}
}
}


第二遍:

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

代码如下:

public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return;
Map<Integer,ListNode> map = new HashMap<Integer,ListNode>();
ListNode pre = head;
int index = 0;
while(pre != null){
map.put(index,pre);
index++;
pre = pre.next;
}
for(int i = 0; i < (index - 1)>>1; i++){
ListNode small = map.get(i);
ListNode big = map.get(index - 1- i);
big.next = small.next;
small.next = big;
}
map.get(index>>1).next = null;
return;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: