Linked List Cycle
思路一: 用 set 记录每个节点的 hashCode,如果遇到重复,说明是循环
public boolean hasCycle(ListNode head) {
Set<Integer> set = new HashSet<>();
while (head != null) {
if (set.contains(head.hashCode())) {
return true;
}
set.add(head.hashCode());
head = head.next;
}
return false;
}
思路二: 快慢指针,一个每次进一步,一个每次进两步,如果是循环链表,他们一定会相遇
public boolean hasCycle(ListNode head) {
ListNode h1 = head;
ListNode h2 = head;
while (h2 != null) {
h2 = h2.next;
if (h2 == null) return false;
h2 = h2.next;
h1 = h1.next;
if (h2 == h1) return true;
}
return false;
}
标签:head,set,return,141,h2,h1,easy,ListNode,leetcode
From: https://www.cnblogs.com/iyiluo/p/16804869.html