编程语言
首页 > 编程语言> > 判断链表里是否有环(算法)

判断链表里是否有环(算法)

作者:互联网

思路:采用快慢指针,若有环 快慢指针一定会在某处相等

public boolean checkCycle(ListNode head){

    if(head==null)
        return fasle;
    ListNode slow = head;
    ListNode fast = head;
    
    while(fast!=null&&fast.next!=null){
        slow = slow.next;
        fast = fast.next.next;
        if(slow==fast)
            return true;
    }
    return false;
}

 

标签:head,slow,return,fast,next,链表,算法,有环,null
来源: https://www.cnblogs.com/QZi-Me/p/15797515.html