public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> visited = new HashSet<ListNode>();
ListNode pos = head;
while (pos!=null){
//遇到遍历过的节点就跳出
if(visited.contains(pos)){
return pos;
}else {
visited.add(pos);
}
pos=pos.next;
}
return null;
}
}
2、两个指针
fast 与 slow。它们起始都位于链表的头部。随后,slow 指针每次向后移动一个位置,而 fast 指针向后移动两个位置。如果链表中存在环,则 fast 指针最终将再次与 slow 指针在环中相遇。
public class Solution {
public ListNode detectCycle(ListNode head) {
//双指针
if(head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
// 当 fast 指针与 slow 指针相遇时
while (fast!=null&& fast.next != null){
fast=fast.next.next;
slow=slow.next;
if (fast == slow) {
ListNode check = head;
while (check != slow) { // check 指针与 slow 指针相遇于入环点
check = check.next;
slow = slow.next;
}
return check;
}
}
return null;
}
}
力扣