//链表定义
typedef struct Node
{
Node(const int& value)
: m_value(value)
, m_pNext(NULL)
{}
int m_value;
Node* m_pNext;
}Node, *pNode;
//判断链表是否带环
pair<pNode, bool> IsExistsLoop(pNode pHead)
{
assert(pHead);
pNode fast = pHead;
pNode slow = pHead;
while (fast&&fast->m_pNext)
{
fast = fast->m_pNext->m_pNext;
slow = slow->m_pNext;
if (fast == slow)
return make_pair(fast, true);//fast为交点
}
//不带环
return make_pair(fast, false);
}
//求环的长度
int length(pNode pHead)
{
assert(pHead);
if (!IsExistsLoop(pHead).second)
return 0;
pNode Node = IsExistsLoop(pHead).first;
pNode pCur = Node->m_pNext;
int count = 1;
while (pCur!=Node)
{
count++;
pCur = pCur->m_pNext;
}
return count;
}
//求环的入口点,一个从头走,一个从交点处走相遇即是入口点
pNode FindLoopPort(pNode pHead)
{
assert(pHead);
pNode node = IsExistsLoop(pHead).first;
pNode pCur = pHead;
while (pCur!=node)
{
pCur = pCur->m_pNext;
node = node->m_pNext;
}
return pCur;
}
判断链表是否带环?若带环求环的长度?若带环求环的入口点?
最新推荐文章于 2021-07-17 19:55:44 发布