/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
HashSet<ListNode> hashSet = new HashSet<ListNode>();
while (head != null) {
if (hashSet.contains(head))
return true;
hashSet.add(head);
head = head.next;
}
return false;
}
}
第一种无脑HashSet存储节点 ,会调用contains和add方法即可。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode slowNode = head, fastNode = head;
while (fastNode.next != null && fastNode.next.next != null) {
slowNode = slowNode.next;
fastNode = fastNode.next.next;
if (slowNode == fastNode) {
return true;
}
}
return false;
}
}
第二种双节点,快节点每次加2,慢节点每次加1,开始追逐。若两节点相同即有环,