C++筆試題之運用快慢指針判斷鏈表中是否有環(huán),并計算環(huán)的長度
判斷鏈表中是否有環(huán)最經(jīng)典的方法就是快慢指針,同時也是面試官大多想要得到的答案。
? ? ? ?快指針pf(f就是fast的縮寫)每次移動2個節(jié)點,慢指針ps(s為slow的縮寫)每次移動1個節(jié)點,如果快指針能夠追上慢指針,那就說明其中有一個環(huán),否則不存在環(huán)。
? ? ? ?這個方法的時間復(fù)雜度為O(n),空間復(fù)雜度為O(1),實際使用兩個指針。
原理
? ? ? ?鏈表存在環(huán),則fast和slow兩指針必然會在slow對鏈表完成一次遍歷之前相遇,證明如下:
? ? ? ?slow首次在A點進(jìn)入環(huán)路時,fast一定在環(huán)中的B點某處。設(shè)此時slow距鏈表頭head長為x,B點距A點長度為y,環(huán)周長為s。因為fast和slow的步差為1,每次追上1個單位長度,所以slow前行距離為y的時候,恰好會被fast在M點追上。因為y<s,所以slow尚未完成一次遍歷。
? ? ? ?fast和slow相遇了,可以肯定的是這兩個指針肯定是在環(huán)上相遇的。此時,還是繼續(xù)一快一慢,根據(jù)上面得到的規(guī)律,經(jīng)過環(huán)長s,這兩個指針第二次相遇。這樣,我們可以得到環(huán)中一共有多少個節(jié)點,即為環(huán)的長度。
實現(xiàn)
#includeusing?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)//加個判斷,如果環(huán)中元素打印完了就退出,否則會無限循環(huán)
????????????????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;???????//環(huán)長度
????while?(?fast?!=?slow?)//再次相遇
????{
????????slow?=?slow->next;
????????fast?=?fast->next->next;
????????length?++;????????//累加
????}
????return?length;
}
Node*?Init(int?num)?//?創(chuàng)建環(huán)形鏈表
{
????if?(num?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;//讓最后一個元素的指針域指向頭結(jié)點,形成環(huán)
????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;
}輸出結(jié)果
參考鏈接:https://blog.csdn.net/sdujava2011/article/details/39738313





