*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;
}
}
}
第一步找到中间 第二步把后半部分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;
}
}
}
相关文章推荐
- jsp片段
- 本人博客排名(2015年10月1日:第67408名)
- *LeetCode-Sort List
- GIT笔记
- 网站并发300就很慢
- CSDN博客下载器 CSDNBlogDownloader
- android中的内存问题(一)
- 面向对象编程 示例 日期默认设置、更改、显示
- **LeetCode-Count Complete Tree Nodes
- 四则运算
- 【离散数学】Warshall算法实现 传递闭包对应矩阵
- Python使用模块Pyserial模块报<ImportError:No module named tools.list_ports>
- Delphi IDHTTP用法详解(六种用法)
- 使用ntfs的磁盘映射功能
- 费波拉奇 递归
- PL/SQL Developer、DbVisualizer 远程连接Oracle
- 写在国庆之前
- Ember.js 入门指南——异步路由
- MAVEN 错误
- php中的脚本加速扩展opcache