链接:环形链表
解决环形链表有两个关键的问题点:(1)怎么确定为环?(2)怎么确定如环节点?
(1)确定存在环结构的方法:1.快慢指针法 2. HashSet法
思路一:Fast指针走一次走两步,slow指针一次走一步,Fast的相对于slow指针的速度为1,因此若存在环结构,则两指针一定会相遇。
思路二:HashSet法,遍历链表,将元素存入set集合中,当出现第一个重复元素,则为入口节点。
(2)确定环的入口节点:fast指针指回头结点,slow指针指向相遇节点,每次移动一步,当fast=slow时即为入口节点。
代码如下:
/**
* 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) {
if(head==null||head.next==null||head.next.next==null) return null;
ListNode fast=head.next.next;
ListNode slow=head.next;
while(fast!=slow){
if(fast==null||fast.next==null||fast.next.next==null) return null;
fast = fast.next.next;
slow = slow.next;
}
fast = head;
while(fast!=slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}