慢指针每次都slow=slow->next;
而快指针每次都quick=quick->next->next;
如果slow==quick;
附上转载链接https://blog.csdn.net/kiripeng/article/details/81078493
#include "stdafx.h"
#include "iostream"
struct Node
{
Node() : pNext(nullptr) {};
Node* pNext;
};
bool IsRing(Node* pHead)
{
if (!pHead || !pHead->pNext)
{
return false;
}
Node* pSlow = pHead;
Node* pQuick = pHead->pNext;
while (pSlow && pQuick && pQuick->pNext && pSlow != pQuick)
{
pSlow = pSlow->pNext;
pQuick = pQuick->pNext->pNext;
}
return pSlow == pQuick;
}
int main()
{
Node* pNode_1 = new Node;
Node* pNode_2 = new Node;
Node* pNode_3 = new Node;
Node* pNode_4 = new Node;
Node* pNode_5 = new Node;
Node* pNode_6 = new Node;
//构造闭环
pNode_1->pNext = pNode_2;
pNode_2->pNext = pNode_3;
pNode_3->pNext = pNode_4;
pNode_4->pNext = pNode_5;
pNode_5->pNext = pNode_6;
pNode_6->pNext = pNode_3;
std::cout << IsRing(pNode_1) << std::endl;
getchar();
return 0;
}