首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >如何判断一个单链表是循环链表

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

作者头像
用户4148957
发布2022-06-14 08:36:16
发布2022-06-14 08:36:16
74100
代码可运行
举报
文章被收录于专栏:C/C++与音视频C/C++与音视频
运行总次数:0
代码可运行

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
 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014-08-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档