在Is there a loop(上)中,咱們判斷了一個單向鏈表有沒有環,接下來咱們繼續探索if有環,環的長度以及環的入口點。限於篇幅,再次不貼完整代碼!oop
/******************************************************************** created:2015年1月23日 00:34:45 author: Jackery purpose: Is there a loop ? 《Continue》 *********************************************************************/ //計算環的長度 /*對於其中的stepfast與stepslow能與能相遇這個問題,不太好理解,涉及到 相似歐拉回路的問題,胡運權的運籌學上面有相關相似講解,不過 你徹底能夠寫個小demo去驗證,對於這個換是奇數、偶數我都驗證了 ,都是可行的*/ int LoopLength(pNode pHead) { if(isLoop(pHead) == false) return 0; pNode stepfast = pHead; pNode stepslow = pHead; int length = 0; bool begin = false; bool agian = false; while( stepfast != NULL && stepfast->next != NULL) { stepfast = stepfast->next->next; stepslow = stepslow->next; //超兩圈後中止計數,跳出循環 if(stepfast == stepslow && agian == true) break; //超一圈後開始計數 if(stepfast == stepslow && agian == false) { begin = true; agian = true; } //計數 if(begin == true) ++length; } return length; } //求出環的入口點 Node* FindLoopEntrance(pNode pHead) { pNode stepfast = pHead; pNode stepslow = pHead; while( stepfast != NULL && stepfast->next != NULL) { stepfast = stepfast->next->next; stepslow = stepslow->next; //若是有環,則stepfast會超過stepslow一圈 if(stepfast == stepslow) { break; } } if(stepfast == NULL || stepfast->next == NULL) return NULL; stepslow = pHead; while(stepslow != stepfast) { stepslow = stepslow->next; stepfast = stepfast->next; } return stepslow; }