题目描述:
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
思路:第一种方法:快慢指针,fast每次走两步,slow每次走一步,如果这两个指针会相遇,则说明有环。
要判断入口是哪里,可以 让slow指针再回到起点,两个指针都一步一步走,最后就会在入口相遇
第二种方法:使用hash表,遍历链表把节点的值放大hash表中,如果第二次出现,那就是循环的入口
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode slow=new ListNode(0);
slow=pHead;
ListNode fast=new ListNode(0);
fast=slow;
while(fast!=null && fast.next!=null ){
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
break;
}
if(fast==null ||fast.next==null){
return null;
}
slow=pHead;
while(fast!=slow){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}
import java.util.HashSet;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
HashSet<ListNode> s=new HashSet<>();
while(pHead!=null){
if(s.contains(pHead)){
return pHead;
}
s.add(pHead);
pHead=pHead.next;
}
return null;
}
}