鏈表--查看鏈表是否含有環(不一樣的方法)

雙指針法,一個快指針,一個慢指針,鏈表若有環的話,快指針必然會與慢指針相遇

<span style="font-size:18px;">typedef struct _node
{
    int data;
    struct _node *next;
}node,*pnode;</span>

int FindLoop(node *head)
{
	node *p = NULL;
	node *q = NULL;
	if (head == NULL)
		return 0;
	p = head;
	q = head->next;
	while (p!=NULL &&
		 q!=NULL&&q->next!=NULL&&p!=q) 
        {
		p = p->next;
		q = q->next->next
	}
	if (p==q)
		return 1;
	else
		return 0;
}


同樣是使用快慢指針找到換的入口點

node *FindLoop(node *head)
{
	node *pc = head;
	node *pf = NULL;
	if (!pc)
		return NULL;
	while (pc)
	{
		pf = head;
		while(pf && pf != pc)
		{
		//當前結點的下一個結點是它前面的某個結點或者是它自己,則爲循環處
				if (pc->next == pf || pc->next == pc)
					return pc->next;
				pf = pf->next;
		}
		pc = pc->next;
	}
	return NULL;
}





点赞