原文:https://blog.youkuaiyun.com/caoshangpa/article/details/80363335
判断链表是否有环的经典的方法是快慢指针的方法。
快指针pf每次移动两个节点,慢指针ps每次移动一个节点,如果指针可以追上慢指针,那就说明其中有一个环,反之没有。

结论:链表存在环,则fast和slow两指针必然会在slow对链表完成一次遍历之前相遇。
证明: slow首次在A点进入环路时,fast一定在环中的B点某处。设此时slow距链表头head长为x,B点距A点长度为y,环周长为s。因为fast和slow的步差为1,每次追上1个单位长度,所以slow前行距离为y的时候,恰好会被fast在M点追上。因为y<s,所以slow尚未完成一次遍历。
fast和slow相遇了,可以肯定的是这两个指针肯定是在环上相遇的。此时,还是继续一快一慢,根据上面得到的规律,经过环长s,这两个指针第二次相遇。这样,我们可以得到环中一共有多少个节点,即为环的长度。
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void Display(Node *head)// 打印链表
{
if (head == NULL)
{
cout << "the list is empty" << endl;
return;
}
else
{
Node *p = head;
while (p)
{
cout << p->data << " ";
p = p->next;
if(p->data==head->data)//加个判断,如果环中元素打印完了就退出,否则会无限循环
break;
}
}
cout << endl;
}
bool IsExistLoop(Node* head)
{
Node *slow = head, *fast = head;
while ( fast && fast->next )
{
slow = slow->next;
fast = fast->next->next;
if ( slow == fast )
break;
}
return !(fast == NULL || fast->next == NULL);
}
int GetLoopLength(Node* head)
{
Node *slow = head, *fast = head;
while ( fast && fast->next )
{
slow = slow->next;
fast = fast->next->next;
if ( slow == fast )//第一次相遇
break;
}
slow = slow->next;
fast = fast->next->next;
int length = 1; //环长度
while ( fast != slow )//再次相遇
{
slow = slow->next;
fast = fast->next->next;
length ++; //累加
}
return length;
}
Node* Init(int num) // 创建环形链表
{
if (num <= 0)
return NULL;
Node* cur = NULL;
Node* head = NULL;
Node* node = (Node*)malloc(sizeof(Node));
node->data = 1;
head = cur = node;
for (int i = 1; i < num; i++)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = i + 1;
cur->next = node;
cur = node;
}
cur->next = head;//让最后一个元素的指针域指向头结点,形成环
return head;
}
int main( )
{
Node* list = NULL;
list = Init(10);
Display(list);
if(IsExistLoop(list))
{
cout<<"this list has loop"<<endl;
int length=GetLoopLength(list);
cout<<"loop length: "<<length<<endl;
}
else
{
cout<<"this list do not has loop"<<endl;
}
system("pause");
return 0;
}
本文介绍了一种使用快慢指针法检测链表中是否存在环的经典算法,并详细解释了其工作原理。通过该算法,不仅可以判断链表是否包含环,还可以进一步计算出环的长度,即环中节点的数量。
261

被折叠的 条评论
为什么被折叠?



