单链表有环,是指单链表的最后一个节点的指针指向了链表中的某个结点(通常单链表的最后一个节点的指针域是空的)。试编写算法判断单链表是否存在环。
#include <iostream>
typedef struct node{
int data;
node* next;
}node,*list;
list Init()
{
list head=(list) malloc(sizeof (node));
head->next= nullptr;
head->data=-1;
return head;
}
list Buynewnode(int x)
{
list tmp=new node;
tmp->next= nullptr;
tmp->data=x;
return tmp;
}
void print(list head)
{
for(list pointer=head->next;pointer!= nullptr;pointer=pointer->next) {
printf("%3d",pointer->data);
}
puts("");
}
void is_cir(list head)
{
list slow=head,fast=head;
while(fast)
{
slow=slow->next;
fast=fast->next;
if(fast) {
fast=fast->next;
}
else break;
if(fast==slow) {
printf("there is a circle\n");
return ;
}
}
printf("there is no circle\n");
return;
}
int main() {
list head=Init();
list pointer=head;
list record= nullptr;
//制造环
for(int i=0;i<10;i++)
{
if(i==6) record=pointer;
pointer=pointer->next= Buynewnode(i+1);
}
pointer->next=record;
is_cir(head);
list head2=Init();
pointer=head2;
record= nullptr;
for(int i=0;i<10;i++)
{
pointer=pointer->next= Buynewnode(i+1);
}
is_cir(head2);
return 0;
}