设两个指针,初始时指向同一节点(任意),然后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); //清理内存
}
测试程序如下:
#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); //清理内存
}