方法1:hash表!
/**
* 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) {
ListNode curA=head;
HashSet<ListNode>set=new HashSet<>();//感觉哈希表好方便,啥都可以往里面装,这玩意还可以存链表。
while(curA!=null){
if(set.contains(curA))return curA;
set.add(curA);
curA=curA.next;
}
return null;
}
}
方法2:快慢指针:
/**
* 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)return null;
ListNode fast=head;
ListNode slow=head;
while(fast!=null){
slow=slow.next;
if(fast.next!=null){
fast=fast.next.next;
}else{
return null;
}
if(fast==slow){
ListNode ptr=head;//建立临时指针,ptr和slow相遇即为入环点
while(ptr!=slow){
ptr=ptr.next;
slow=slow.next;
}
return ptr;
}
}
return null;
}
}
/**
* 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)return null;
ListNode fast=head;
ListNode slow=head;
while(fast!=null){
slow=slow.next;
if(fast.next!=null){
fast=fast.next.next;
}else{
return null;
}
if(fast==slow){
ListNode ptr=head;
while(ptr!=slow){
ptr=ptr.next;
slow=slow.next;
}
return ptr;
}
}
return null;
}
}