算法思想: A跑一步,B跑两步, 如果有环形区, B一定会与A相遇.
#include <iostream>
#include <string>
using namespace std;
typedef struct list_node
{
int x;
struct list_node* next;
}node, *pnode;
bool isCircle(pnode list)
{
pnode quick=list, slow=list;//快慢指针
while(1)
{
if(quick==NULL || slow == NULL)//可以到达链表末尾说明无环
return false;
quick = quick->next;
if(quick == NULL)
return false;
quick = quick->next;
slow = slow->next;
if(slow==quick)//慢指针赶上快指针说明有环
return true;
}
}
int main()
{
pnode list = NULL, temp;
for(int i=1;i<=10;i++)
{
pnode pn = new node;
pn->x = i;
pn->next = list;
list = pn;
}
temp = list;
for(int i=0;i<10;i++, temp=temp->next)
cout<<temp->x<<" ";
cout<<endl;
if(isCircle(list))
cout<<"有环"<<endl;
else
cout<<"无环"<<endl;
//手工构造一个环
pnode tail = list;
while(tail->next != NULL)
tail = tail->next;
tail->next = list;
if(isCircle(list))
cout<<"有环"<<endl;
else
cout<<"无环"<<endl;
for(int i=0;i<10;i++)
{
temp = list->next;
delete list;
list = temp;
}
return 0;
}