简单并带有错误的环形单链表检测代码

LinkedList* IsCyclicLinkedList (LinkedList* pHead) 
 {    
  LinkedList* pCur;     
  LinkedList* pStart;     
  while (pCur != NULL)   
   {        
    for ( ; ; )    
      {        
      if (pStart == pCur->next)           
       return pStart;     
         pStart = pStart->next;     
     }  
        pCur = pCur->next; 
    }     
  return pStart;  
}

修改

LinkedList* IsCyclicLinkedList (LinkedList* pHead)  
{  
    LinkedList* pCur;  
    LinkedList* pStart;  
   int  temp=0;
   int lenth=0;
    while (pCur != NULL)  //pCur不可能为NULL,若有环
    {  
	lenth = pcur-pstart;
        if (length!=temp)  
           	  return pcur
        pCur = pCur->next;  
	temp++;
    }  
    return pStart;  
}  


思想是:通过两个指针之间的长度与实际比较的次数相比较!

二:使用快慢指针

// 判断链表中是否有环
bool IsExitLoop(LinkList *head)
{
	LinkList *pslow = head;
	LinkList *pfast = head;
	while(pfast != NULL && pfast->next != NULL)
	{
		pslow = pslow->next;        // 每次前进一步
		pfast = pfast->next->next;  // 每次前进二步
		if(pslow == pfast)          // 两个指针相遇,说明存在环
			return true;
	}
	return false;    // 没有环
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值