import java.util.HashSet;
import java.util.Set;
public class LeetCode141 {
public boolean hasCycle(ListNode head) {
Set<ListNode> listNodes = new HashSet<ListNode>();
while (head != null){
listNodes.add(head);//将链表节点存入集合
head = head.next;//移动到下一位
if (listNodes.contains(head)){
return true;
} //判断当前节点在集合中是否已经存在,若存在表明链表存在环,返回true
}
return false;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
141. 环形链表
最新推荐文章于 2025-07-29 13:47:21 发布