Leetcode – Linked List Cycle判断一个链表是否有环

https://www.programcreek.com/2012/12/leetcode-linked-list-cycle/
给定一个链表,确定其中是否有环。

分析

如果我们有2个指针-快和慢。如果存在一个圆,可以保证快的人会遇到慢的人。

下图可以演示该问题:
linked-list-cycle
Java Solution

public class Solution {
    
    
    public boolean hasCycle(ListNode head) {
    
    
        ListNode fast = head;
        ListNode slow = head;
 
        while(fast != null && fast.next != null){
    
    
            slow = slow.next;
            fast = fast.next.next;
 
            if(slow == fast)
                return true;
        }
 
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/abu935009066/article/details/112337396
今日推荐