题目链接:142. 环形链表 II
https://leetcode.cn/problems/linked-list-cycle-ii/

简言之:给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
方法一(使用java的哈希表):
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
HashSet<ListNode> visited = new HashSet<ListNode>();
ListNode p = head;
while(p != null){
if(!visited.contains(p))
{
visited.add(p);
p = p.next;
}
else return p;
}
return null;
}
}
方法二(使用快慢指针):
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
// https://leetcode.cn/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode-solution/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=head;
ListNode fast = head;
// 快慢指针方法判断是否有环
while(fast != null && fast.next !=null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow) break;
}
// fast 遇到空指针说明没有环
if(fast == null || fast.next == null)
return null;
// 重新指向头结点
slow = head;
// 快慢指针同步前进,相交点就是环起点
while(fast != slow)
{
fast = fast.next;
slow = slow.next;
}
return fast;
}
}