Use the two pointer approach.
Rough code:
Hope it helps.Code:bool ContainsLoop (Node *pNode) { Node *pSlowptr = pNode; Node *pFastptr = pNode->pNext; while (pFastptr != NULL || pSlowptr != NULL) { if (pSlowptr == pFastptr) return true; pSlowptr = pSlowptr->pNext; if (pFastptr->pNext) pFastptr = pFastptr->pNext->pNext; else pFastptr = NULL; } return false;




Reply With Quote