Given a single-chain table, check whether the linked list contains a ring structure. This topic is mainly based on the characteristics of the ring, using two pointers with different step sizes to move forward in one direction. If there is a ring, the two pointers must meet each other.
# Include < Stdio. h >
# Include < Malloc. h >
Typedef Struct Lnode {
Int Data;
Struct Lnode * Next;
} Lnode;
Int Isloop (lnode * Head ){
Lnode * P = Head, * Q = Head;
While (Q && Q -> Next ){
P = P -> Next;
Q = Q -> Next -> Next;
If (P = Q) Break ;
}
Return ! (Q = Null | Q -> Next = Null );
}
Int Main (){
Lnode * Head = (Lnode * ) Malloc ( Sizeof (Lnode ));
Lnode * Curr = Head;
Lnode * Start = NULL;
Head -> Next = NULL;
Int I;
For (I = 0 ; I < 10 ; I ++ ){
Curr -> Next = (Lnode * ) Malloc ( Sizeof (Lnode ));
Curr = Curr -> Next;
Curr -> Next = NULL;
If (I = 5 ) Start = Curr;
}
Curr -> Next = Start;
Printf ( " % D " , Isloop (head ));
}