This is a classic Microsoft written test question. The two pointers h1 and h2 traverse the singly linked list from the beginning. h1 moves forward 1 step each time, and h2 moves forward 2 steps each time. If h2 encounters NULL, it means that the ring does not exist. ; If h2 touches h1 that should be behind it, it means that a loop exists (that is, a loop occurs).
If the ring does not exist, h2 must encounter NULL first:
If the ring exists, h2 and h1 will definitely meet, and the meeting point is within the ring: h2 traverses faster than h1, and will definitely not meet at the beginning of the non-ring linked list, so when h1 and h2 both enter the ring Finally, each movement of h2 will reduce the gap between h2 and h1 in the forward direction by 1. Finally, the gap between h1 and h2 will be reduced to 0, that is, they meet.
public static void main(String args[]){
SingleList list = new SingleList();
for(int i=0;i<100;i++){
list.add(i);
}
System.out.print(SingleList.isExistingLoop(list));
}
}
public Node(Object value){
this.data = value;
}
publicNode(){
this.data = null;
this.next = null;
}
}
private void init(){
this.size = 0;
this.head = new Node();
}
public SingleList(){
init();
}
public boolean contains(Object value){
boolean flag = false;
Node p = head.next;
while(p!=null){
if(value.equals(p.data)){
flag = true;
break;
}else(
p = p.next;
)
}
return flag;
}
public boolean add(Object value){
if(contains(value))
return false;
else{
Node p = new Node(value);
p.next=head.next;
head.next = p;
size++;
}
return true;
}
}