首页 > 其他 > 详细

环形链表问题

时间:2021-07-03 17:01:05      阅读:14      评论:0      收藏:0      [点我收藏+]
  1. 环形链表

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null)return false;
        ListNode p1=head;
        ListNode p2=head;
        do{
            p1=p1.next;
            if(p2==null||p2.next==null)return false;
            p2=p2.next.next;
        }while(p1!=p2);
        return true;
    }
}
  1. 环形链表 II

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null||head.next==null)return null;
        ListNode slow=head;
        ListNode fast=head;//这个初始化有影响?有的。要从首节点开始。
        do{//这里改成while(slow!=fast)的话就不会进入这个循环了
            slow=slow.next;
            if(fast==null||fast.next==null)return null;
            fast=fast.next.next;
        }while(slow!=fast);

        fast=head;
        while(slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return fast;
    }
}

环形链表问题

原文:https://www.cnblogs.com/wsshub/p/14966473.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!