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

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

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

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

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
 }


猜你喜欢

转载自blog.csdn.net/fengliang191/article/details/38641519