判断给定链表中是否有环

给定一个链表,判断链表中是否有环。

示例:
输入:head = [3,2,0,-4]
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
在这里插入图片描述

思路:
设定一个fast一次走两步,slow一次走一步,当fast=slow时,此时证明单链表中有环。

小思考:
本题给出的思路是fast是slow的二倍,那么请思考一下,fast可不可以是slow的三倍?四倍?甚至更多倍呢?

答案肯定是可以的呢,只不过是运算时间的不同而已。但是事实证明,当fast是slow的二倍的时候走的是最少的,即运算时间是最短的。

代码如下:

public void creteLoop(){
        ListNode cur = this.head;
        while(cur.next != null) {
            cur = cur.next;
        }
        cur.next = this.head.next.next;
    }
public boolean hasCycle(){
        ListNode fast = this.head;
        ListNode slow = this.head;
        while(fast != null && fast .next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast) {
                break;
            }
        }
        if(fast == null || fast.next == null) {
            return false;
        }
        return true;
    }

代码测试:

public static void main(String[] args) {
        SingleList singleList = new SingleList();
      
        singleList.addLast(1);
        singleList.addLast(2);
        singleList.addLast(7);
        singleList.addLast(8);
        singleList.addLast(5);
        singleList.creteLoop();
        boolean flg = singleList.hasCycle();
        System.out.println(flg);
//运行结果:true

public static void main(String[] args) {
        SingleList singleList = new SingleList();

        singleList.addLast(1);
        singleList.addLast(2);
        singleList.addLast(7);
        singleList.addLast(8);
        singleList.addLast(5);
       
        boolean flg = singleList.hasCycle();
        System.out.println(flg);
//运行结果:false
发布了43 篇原创文章 · 获赞 41 · 访问量 1785

猜你喜欢

转载自blog.csdn.net/weixin_45662626/article/details/103211005