1 怎么获取中间点?
小明每秒跑200米
小华每秒跑100米
跑道长1000米
当小明到终点时,小华的位置equals the mid of the runway
所以,一样的道理,如果我要快速找到一个链表的中点呢?
首先,得有一个小明:faster
然后,有一个小华:lower
当faster arrive the destination while the lower touch the mid point
终止条件就是faster的next为null
既然要判定faster的next为null,那么faster一定不能为null
如果你写
if(faster.next != null)
{
...
}
很大程度上,你会出问题
因为往往这个时候,faster is null
所以,必须加上判定
if(faster.next != null&&faster!=null)
{
...
}
终止条件有了,就开始跑呗:
public ListNode divideDoubleSegment(ListNode head){
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
2 怎么从中间点截断链表?
截断链表很简单,让slow.next = null就可以了
but...
对于head而言,它的终点确实就到slow为止,但是,对于归并来说,我还希望知道第二段啊!!!
所以,这个时候,直接操作slow并不可取,因为意味着你拿不到归并的right segment
而简单的做法就是:
public ListNode divideDoubleSegment(ListNode head){
ListNode preEnd = head;
ListNode slow = head;
ListNode fast = head;
ListNode nextSegmentBegin = head;
while (fast != null && fast.next != null) {
preEnd = slow;
slow = slow.next;
fast = fast.next.next;
}
preEnd.next = null;
return slow;
}