如何判断一个单链表是循环链表

如何判断一个单链表是循环链表

1.循环链表的特点是收尾相接,没有头指针,也没有尾指针。如果去遍历循环链表,则是死循环。

2.这里判断循环链表的方法是; 用两个指针,一个指针是块指针(跳一个节点遍历),遍历快(p=p->netxt->next),一个指针逐步遍历,慢指针。

如果在遍历当中,如果发现这两个指针有可能是出现NULL指针的话,那边它是单链表。否则是单链表(本来这个证明已经够了,但如何让死循环的函数停止,给我们一个返回一个循环链表的结构呢?这里的方法是:如果在循环链表中,慢指针一定可能和快指针重叠,(类似于运动员超跑一样)。

代码语言:javascript代码运行次数:0运行复制typedef struct node

{

int data;

struct node *next;

}Node,*pnode;

int is_Clink( pnode p)

{

pnode fastpoint,slowpoint;

fastpoint=p;

slowpoint = p;

while(1)

{

if(slowpoint==NULL||fastpoint==NULL)

printf("This is linklist\n");

return 1

slowpoint=slowpoint->next;

fastpoint=fastpoint->next->next;

if (slowpoint==fastpoint||fastpoint->next==slowpoint)

printf("The si Clink\n");

return 0;

}

}

/*做一个小改进,优化一下代码结构如下:*/

int is_Clink( pnode p)

{

pnode fastpoint,slowpoint;

fastpoint=p;

slowpoint = p;

while(slowpoint &&fastpoint)

{

slowpoint=slowpoint->next;

fastpoint=fastpoint->next->next;

if (slowpoint==fastpoint||fastpoint->next==slowpoint)

printf("The si Clink\n");

return 0;

}

printf("This is linklist\n");

return 1

}

相关推荐

uc浏览器隐藏图片在哪里
家庭版microsoft365

uc浏览器隐藏图片在哪里

⌛ 2025-08-03 👁️ 1237
rtb是什么意思?rtb产品卖点
约彩365苹果在线安装

rtb是什么意思?rtb产品卖点

⌛ 2025-07-04 👁️ 4839
基本解释
约彩365苹果在线安装

基本解释

⌛ 2025-07-01 👁️ 8311