Programming questions:
Q1. how can I determine whether a ring exists in a linked list? (The linked list is not necessarily a Circular Single-chain table or double-chain table .)
A: set two pointers to chase
Solution 1:
Bool circleinlist (link * phead)
{
If (phead = NULL | phead-> next = NULL) // No node or only one node and no self-ring
{
Return (false );
}
If (phead-> next = phead) // self-ring
{
Return (true );
}
Link * ptemp1 = phead; // Step 1
Link * ptemp = phead-> next; // Step 2
While (ptemp! = Ptemp1 & ptemp! = NULL & ptemp-> next! = NULL)
{
Ptemp1 = ptemp1-> next;
Ptemp = ptemp-> next;
}
If (ptemp = ptemp1)
{
Return (true );
}
Return (false );
}
Solution 2:
bool circleinlist (link * phead)
{< br> If (phead = NULL) return false;
link * ptemp;
link * ptemp2;
int I, j;
for (I = 0, ptemp = phead; ptemp; I ++, ptemp = ptemp-> next)
{< br> for (j = 0, ptemp2 = phead; j next)
{< br> If (ptemp2 = ptemp) return true;
}< BR >}< br> return false;
}