package 刷题.leedcode142;
//找环得入口点
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
方法一:
package 刷题.leedcode142;
//快慢指针法
public class Solution1 {
public ListNode detectCycle(ListNode head){
if(head == null || head.next == null){
return null;
}
ListNode prev = head;
ListNode cur = head;
while(cur != null && cur.next != null){
prev = prev.next;
cur = cur.next.next;
if(prev == cur){
ListNode ptr = head;
while(ptr != prev){
ptr = ptr.next;
prev = prev.next;
}
return ptr;
}
}
return null;
}
}
方法二:
package 刷题.leedcode142;
import java.util.HashSet;
import java.util.Set;
//哈希表
public class Solution2 {
public ListNode detectCycle(ListNode head) {
//遍历链表每个结点并记录下来,若再次遇到,返回即可
/*
ListNode prev = head;
Set<ListNode> seen = new HashSet<ListNode>();
while(prev != null){
if(seen.contains(prev)){
return prev;
}else{
seen.add(prev);
}
prev = prev.next;
}
return null;
*/
Set<ListNode> seen = new HashSet<>();
ListNode prev = head;
while(prev != null){
if(!seen.add(prev)){
return prev;
}
prev = prev.next;
}
return null;
}
}