判断单链表是否带环?若带环,求环的长度?求环的入口点?(C语言)
生活随笔
收集整理的這篇文章主要介紹了
判断单链表是否带环?若带环,求环的长度?求环的入口点?(C语言)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
PSListNode HasCycle(PSListNode pHead)
{if ((NULL == pHead) || (NULL == pHead->pNextNode)){return NULL;}else{PSListNode pFast = pHead->pNextNode->pNextNode;PSListNode pSlow = pHead->pNextNode;//利用快慢指針,讓快指針每次走兩步,慢指針每次走一步,要是快指針沒有走到NULL,且快指針與慢指針指向相同就說明是有環while (pFast != pSlow){//快指針要是沒有指向為空,那么慢指針就不可能指向空(快指針走得快)if (NULL == pFast){return;}else{pFast = pFast->pNextNode;pSlow = pSlow->pNextNode; if (NULL == pFast){return;}else{pFast = pFast->pNextNode;}}}return pFast;}
}int GetCyleLen(PSListNode pMeetNode)
{//默認傳的參數是HasCycle函數返回的環中的一個結點if (NULL == pMeetNode){return 0;}else{int nCount = 1;PSListNode pNode = pMeetNode;while (pMeetNode != pNode->pNextNode){pNode = pNode->pNextNode;nCount++;}return nCount;}
}
//pMeetNode參數是用HasCycle函數求鏈表是否有環時pFast指針與pSlow指針的碰撞點
//定律:在鏈表頭,pFast指針與pSlow指針的碰撞點分別設定一個指針,每次各走一步,兩個指針必定相遇,則相遇第一點為環入口點
PSListNode FindEnterNode(PSListNode pHead, PSListNode pMeetNode)
{PSListNode pNode = pHead;if ((NULL == pHead) || (NULL == pMeetNode)){return NULL;}while (pNode != pMeetNode){pNode = pNode->pNextNode;pMeetNode = pMeetNode->pNextNode;}return pNode;
}
總結
以上是生活随笔為你收集整理的判断单链表是否带环?若带环,求环的长度?求环的入口点?(C语言)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html自动图片尺寸,关于html:CS
- 下一篇: opensips mysql 认证_基于