1. 程式人生 > >求單向連結串列的是否有環及環入口

求單向連結串列的是否有環及環入口

參考部落格:https://www.cnblogs.com/dancingrain/p/3405197.html

bool HasLoop(Node* root, Node* &Entry)
{
	if(!root) return false;

	bool bHasLoop = false;
	Entry = nullptr;
	Node* pFast,*pSlow;
	pSlow = pFast = root;

	while(pFast)//pFast->pNext當pFast為nullptr時會報錯:無法計算表示式的值
	{
		pSlow = pSlow->pNext;
		if(!pFast->pNext)	return false;//pFast->pNext當pFast為nullptr時會報錯:無法計算表示式的值
		pFast = pFast->pNext;
		if(!pFast->pNext)	return false;
		pFast = pFast->pNext;
		if(pSlow == pFast)	
		{	
			bHasLoop = true;
			break;
		}
	}
	if(!bHasLoop) return false;

	while(root != pSlow)
	{
		root = root->pNext;
		pSlow = pSlow ->pNext;
	}
	Entry = pSlow;

	return true;
}

測試主函式:

struct Node
{
	Node* pNext;
	int val;
	Node(int v)
	{
		val = v;
		pNext = nullptr;
	}
};

int main()
{
	Node *root = new Node(0);
	Node *curNode = root;
	Node *entrySet;
	for (int i=1;i<=98;i++)
	{
		curNode->pNext = new Node(i);	
		curNode = curNode->pNext;
		if(i == 98) entrySet = curNode;//標記環形連結串列入口
	}
	
	curNode->pNext = new Node(99);//一共100個節點,值為0-99
	curNode->pNext->pNext = entrySet;//構造環形連結串列

	Node* entryGot;
	bool bHasLoop = HasLoop(root,entryGot);

	if(bHasLoop)
		cout << entryGot->val << endl;
	system("pause");
	return 0;
}