在链表里如何发现循环链接?

设两个指针,初始时指向同一节点(任意),然后p不动,q移动,测试q的地址会不会重新指向p的地址.如果重新有p==q,则循环,否则不循环;

测试程序如下:
#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
int data;
struct Node* next;
}node;
node* CreateLinkList(const int *ptr,const int len,bool circle)
{
node* p, *q;
node* head = NULL;
for(int i = 0; i < len; i++)
{
p = (node*) malloc(sizeof(node));
p-> data = ptr[i];
p-> next = NULL;
if(!head)
{
head = p;
q = p;
}
else
{
q-> next = p;
q = p;
}
}
if(circle)
{
p -> next = head;
}
return head;
};
int ClearLinkList(node* ptr, int len)
{
node* p;
for(int i = 0; i < len; i++)
{
p = ptr;
if(ptr-> next)
{
ptr = ptr-> next;
}
free(p);
}
return 1;
};
bool searchLinkList(const node* p, const node* q)
{
while(q-> next)
{
q = q-> next;
if(q == p)
{
printf( "It 's a circle linklist!\n ");
return true;
}
}
printf( "It 's not a circle linklist!\n ");
return false;
}
void main()
{
int arrLen = 20; //数组长度(实际),用于形成测试链表;
node* p, *q;
int array[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
p = q = CreateLinkList(array,arrLen,1); // 设定测试链表,1为循环,0为不循环;
searchLinkList(p,q); //测试;
ClearLinkList(p,arrLen); //清理内存
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值