题目描述
判断一个链表是否有环
题解
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null)
return false;
ListNode slow = head;
ListNode fast = head.next;
while(slow!=null&&fast!=null&&fast.next!=null)
{
if(slow==fast)
return true;
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}

本文介绍了一种使用快慢指针的方法来判断链表中是否存在环。通过遍历链表,快指针每次移动两个节点而慢指针每次移动一个节点,如果两者相遇则说明链表存在环。
1433

被折叠的 条评论
为什么被折叠?



