您的位置:首页 > 其它

LEETCODE Reorder List

2014-06-09 00:45 295 查看

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



就是一个头一个尾直到两边遇见了就算完。

显然数组或者列表的数据结构要明显比链式结构处理容易。对于这种可以转换的,我们建立一个栈,先遍历一次将所有节点都按顺序存下来,再按他的方法来做。

题目需要注意的地方是:

1. head指针是初始指针,因此它的next肯定是从最末尾找。找完这个最末尾就应该跳到前面去找,此时不应该找head。

2. 一头一尾肯定定义两个int型做指针用。start肯定为0,end为length-1。循环条件就是start<end(也就是说start=end跳出)。(若start=1肯定对于长度为2的数组一开始就跳出了)。

3. 因此循环的第二步除了判定是否还满足循环条件外,还应先对start++再进行指针变化操作。否则就指回了head。

4. 改变链表自身结构,或者复制自身链表这种情况,尾节点next一定要制空!

5. 总结这种链表题一定要画图按步骤来做。

public class Solution {
public void reorderList(ListNode head) {
if (head==null){
return;
}
ArrayList<ListNode> stack = new ArrayList<ListNode>();
ListNode newHead = head;
while(newHead!=null){
stack.add(newHead);
newHead = newHead.next;
}
int start = 0;
int end = stack.size()-1;
while(start<end){
head.next = stack.get(end);
head = head.next;
end--;

if(start<end){
start++;
head.next = stack.get(start);
head = head.next;

}
}
head.next = null;

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