This is a classic Microsoft pen exam, that is, two pointers, h1. h2 traverses the single-chain table from the beginning. h1 moves one step forward each time, while h2 moves two steps forward each time. If h2 encounters NULL, indicates that the ring does not exist. If h2 encounters the h1 that should be behind it, it indicates that the ring exists (that is, a ring occurs ).
If the ring does not exist, h2 must first encounter NULL:
If the ring exists, h2 and h1 will certainly encounter each other, And the encounter point is in the ring: h2 is faster than h1 traversal, so it will not encounter the non-ring linked list part at the beginning, so when both h1 and h2 enter the ring, Every time h2 moves, the gap between h2 and h1 in the forward direction will be reduced by 1. Finally, the gap between h1 and h2 will be reduced to 0, that is, encounter
Copy codeThe Code is as follows: package org. myorg;
Public class Test {
Public static boolean isExsitLoop (SingleList ){
Node <T> slow = a. head;
Node <T> fast = a. head; while (fast! = Null & fast. next! = Null ){
Slow = slow. next;
Fast = fast. next. next;
If (slow = fast)
Return true;
}
Return false;
}
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 ));
}
}
Copy codeThe Code is as follows: package org. myorg;
Public class Node {
Public Object data; // The data Object stored by the node
Public Node next; // reference to the next Node
Public Node (Object value ){
This. data = value;
}
Public Node (){
This. data = null;
This. next = null;
}
}
Copy codeThe Code is as follows: package org. myorg;
Public class SingleList {
Private int size;
Private Node head;
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;
}
}