挺烧脑的一道题,这里搜集了一个很好的解答方案
参考自:http://blog.csdn.net/snow_7/article/details/52181049
方法一:
对于一个单链表判断其是否含环的最基本想法是,设置两个指针,一快一慢,其中快指针的步长是慢指针的两倍
对于一个已经含环的单链表,如下图所示:
设环外节点数为x,环中节点数为n,那么对于快慢指针来说,当他们相遇时慢指针还未走完环一圈,而快指针已然走了y圈
由于快指针走的速度是慢指针的两倍,那么此时便满足如下的代数关系:
x+yn+k=2(x+k)
由上式可以得到:
x+k=yn
即:
x=yn-k
当y=1时,同样成立,此时x=n-k
我们可以发现x=n-k 恰好是慢指针从当前节点到环入口节点所需要经过的节点数,也就是说一个新指针从head节点处出发,慢指针从当前位置处出发(也就是k处),两个节点必然相遇于环入口处
方法二:
HashSet不能添加重复的元素,当调用add(Object)方法时,首先会调用Object的hashCode方法判hashCode是否已经存在,如不存在则直接插入元素;如果已存在则调用Object对象的equals方法判断是否返回true,如果为true则说明元素已经存在,如为false则插入元素。
我们根据HashSet的这一特性,从head开始,逐一往HashSet中添加元素,如果出现添加重复元素的话,那么就说明该单链表存在环否则不存在
方法一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) {
boolean flag=false;
if(head==null || head.next==null){
return null;
}
ListNode fast=head;
ListNode low=head;
//find the node that low and fast meeting
while(fast!=null && fast.next!=null){
fast=fast.next.next;
low=low.next;
if(fast==low){
flag=true;
fast=head;
while(fast!=low){
fast=fast.next;
low=low.next;
}
break;
}
}
if(!flag){
return null;
}
return low;
}
}
方法二:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.HashSet;
public class Solution {
public ListNode detectCycle(ListNode head) {
HashSet<ListNode> temp=new HashSet<ListNode>();
while(head!=null && temp.add(head)){
head=head.next;
}
return head;
}
}