算法实验室-14-怎么获取链表的中间节点?怎么从中间截断链表?

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

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值