方法一:使用map來記錄鏈表中的結點是否被訪問,若存在被訪問兩次的結點則說明存在環。
#include "iostream"
#include "map"
using namespace std;
map<node*,int>m;
bool IsLoop(node *head)
{
if(!head)
return false;
node *p=head;
while(p)
{
if(m[p]==0) // 默認值都是0
m[p]=1;
else if(m[p]==1)
return true;
p=p->next;
}
}
方法二:設置兩個指針pSlow,pFast,慢的一次跳一步,快的一次跳兩步,往鏈表末端移動,若慢指針追上了快指針 ,則說明鏈表存在環。此方法速度很快且不需要額外的存儲空間。
bool IsLoop(node *head)
{
node *pSlow=head;
node *pFast=head;
while(pSlow!=NULL && pFast!=NULL)
{
pSlow=pSlow->next;
pFast=pFast->next->next;
if(pSlow==pFast)
return true;
}
return false;
}