解法一:哈希表
用哈希表存储访问过的结点,如果出现重复访问说明存在环。
/**
* 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) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}
解法二:快慢指针
两个指针以不同的速度遍历,一个步长为1,一个步长为2。如果存在环,就像操场上跑步一样,步长大的跑得快,会在某一时刻追上步长小的。
/**
* 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) {
ListNode p1 = head;
ListNode p2 = head;
while ((p1 != null) && (p2 != null)) {
p1 = p1.next;
if (p1 != null) {
p1 = p1.next;
} else {
break;
}
p2 = p2.next;
if (p1 == p2) {
return true;
}
}
return false;
}
}