【链表】判断链表是否有环

双指针:

使用两个指针fast和slow,它们起始都位于链表的头部。

slow每次向后移动一个位置,而fast指针每次移动两个位置。

如果链表中存在环,则fast指针最终再与slow指针在环中相遇。

证明:

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

猜你喜欢

转载自blog.csdn.net/m0_52043808/article/details/124286054
今日推荐