您的位置:首页 > 其它

*LeetCode-Reorder List

2015-10-01 04:03 357 查看
这个题分三步 但是每一步都很多细节 

第一步找到中间 第二步把后半部分reverse 第三步将这两部分按顺序链接

注意第一部分第二部分break开 然后注意后面的head一开始设置成null 再翻转

然后就是连接的时候 注意停止条件

public class Solution {
public void reorderList(ListNode head) {
if ( head == null || head.next == null )
return;
ListNode fast = head;
ListNode slow = head;
ListNode pre = new ListNode(0);
while ( fast != null && fast.next != null ){
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
if ( fast != null ){
slow = slow.next;
pre = pre.next;
} // odd num
ListNode cur = slow.next;
pre.next = null;
slow.next = null;
ListNode temp = new ListNode (0);
while ( cur != null ){
temp = cur.next;
cur.next = slow;
slow = cur;
cur = temp;
}
while ( slow != null ){
ListNode temp1 = head.next;
ListNode temp2 = slow.next;
head.next = slow;
slow.next = temp1;
head = temp1;
slow = temp2;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: