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

来源:互联网 发布:eve欧服 mac 编辑:程序博客网 时间:2024/05/21 04:26

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;    // 没有环}


	
				
		
原创粉丝点击