LinkedList* IsCyclicLinkedList (LinkedList* pHead) { LinkedList* pCur; LinkedList* pStart; while (pCur != NULL) { for ( ; ; ) { if (pStart == pCur->next) return pStart; pStart = pStart->next; } pCur = pCur->next; } return pStart; }
修改
LinkedList* IsCyclicLinkedList (LinkedList* pHead) { LinkedList* pCur; LinkedList* pStart; int temp=0; int lenth=0; while (pCur != NULL) //pCur不可能为NULL,若有环 { lenth = pcur-pstart; if (length!=temp) return pcur pCur = pCur->next; temp++; } return pStart; }
思想是:通过两个指针之间的长度与实际比较的次数相比较!
二:使用快慢指针
// 判断链表中是否有环 bool IsExitLoop(LinkList *head) { LinkList *pslow = head; LinkList *pfast = head; while(pfast != NULL && pfast->next != NULL) { pslow = pslow->next; // 每次前进一步 pfast = pfast->next->next; // 每次前进二步 if(pslow == pfast) // 两个指针相遇,说明存在环 return true; } return false; // 没有环 }