Java的set集合就是不能放相同的东西 刚好利用这一点
package suanfa.Max;
import java.util.HashSet;
import java.util.Set;
public class Double {
//内部类
public static class ListNode{
ListNode next;
int val;
public ListNode(int val,ListNode next){
this.val=val;
this.next=next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode node5=new ListNode(5,null);
ListNode node4=new ListNode(4,node5);
ListNode node3=new ListNode(3,node4);
ListNode node2=new ListNode(2,node3);
ListNode node1=new ListNode(1,node2);
node5.next=node3;//这样就又环了
System.out.println(hasCycle(node1));
System.out.println(hasCycle2(node1));
}
//第二种方法 快慢指针 只要有环 一定能追上 最终相遇
//定义快指针走2格 慢指针走一格
private static boolean hasCycle2(ListNode head) {
// TODO Auto-generated method stub
if(head==null||head.next==null){
return false;
}
ListNode kuai=head.next;
ListNode man=head;
while(man!=kuai){
if(kuai==null||kuai.next==null){
return false;
}
kuai=kuai.next.next;
man=man.next;
}
return true;
}
//第一种方法 java自带的方法集合
public static boolean hasCycle(ListNode head) {
// TODO Auto-generated method stub
//第一种用set集合 应为不能方相同的数字
Set<ListNode> set=new HashSet<ListNode>();
while(head!=null){
if(!set.add(head)){
return true;
}
head=head.next;
}
return false;
}
}