This is a Microsoft Classic pen test, is two pointers h1,h2 start from the beginning to traverse the single linked list, H1 each step forward 1 steps, H2 each step forward 2 steps, if the H2 encountered null, indicating that the ring does not exist, if the H2 encounter should be behind the H1 note ring exists (that is, the rings).
If the ring does not exist, it must be H2 first encountered null:
If the ring exists, H2 and H1 must meet, and meet the point in the ring: H2 than H1 traversal speed, will not be in the beginning of that segment of the chain of the link to meet, so when the h1,h2 into the ring, H2 each move will make H2 and H1 in the direction of the gap between the 1, finally, Will make the gap between the H1 and H2 0, that is, meet
Copy Code code as follows:
Package org.myorg;
public class test{
public static Boolean Isexsitloop (Singlelist a) {
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 Code code as follows:
Package org.myorg;
public class node{
public Object data; Data objects stored by the node
Public Node Next; References to the next node
Public Node (Object value) {
This.data = value;
}
Public Node () {
This.data = null;
This.next = null;
}
}
Copy Code code 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;
}
}