1.快慢指针判断链表有环、寻找环入口、计算环大小的原理
问题:
给定一个链表:
1. 判断链表是否有环。
2. 如果链表有环,请找出环入口。
3. 计算环的大小。
思路:快慢指针
分别定义一个快指针fast和慢指针slow,快指针一次走两步,慢指针一次走一步。如果链表没有环,那么fast最终会指向nullptr;如果链表有环,那么快指针和慢指针最终会相遇。所以,如果最终fast == nullptr,那么判断链表无环;如果最终fast == slow,且fast != nullptr,那么链表有环。
核心代码
寻找环入口
LLNode * LinkedList::entranceOfLoop()
{
LLNode * slow = pHead;
LLNode * fast = pHead;
while(fast && fast->pNext)
{
fast = fast->pNext->pNext;
slow = slow->pNext;
if(fast == slow) break;
}
if(!fast || !fast->pNext) return nullptr;
fast = pHead;
while(fast != slow)
{
fast = fast->pNext;
slow = slow->pNext;
}
return fast;
}
计算环大小
int LinkedList::sizeOfLoop()
{
LLNode * slow = pHead;
LLNode * fast = pHead;
while(fast && fast->pNext)
{
fast = fast->pNext->pNext;
slow = pNext;
if(fast == slow) break;
}
if(!fast || !fast->pNext) return 0;
int size = 1;
fast = fast->pNext->pNext;
slow = slow->pNext;
while(fast != slow)
{
++size;
fast = fast->pNext->pNext;
slow = slow->pNext;
}
return size;
}
来源:CSDN
作者:Joker96410
链接:https://blog.csdn.net/Dxs4396/article/details/104075422