我遇到了一個leetcode 問題(用于鏈接串列的弗洛伊德回圈檢測演算法),其中我注意到指標狀態的奇怪行為。當我在 for 回圈中更改指標狀態時,程式正確執行(指標狀態移動到正確的狀態):
ListNode *detectCycle(ListNode *head) {
if(!head or !head->next)
return nullptr;
ListNode *slow, *fast;
for(slow = head, fast = head; fast && fast->next;)
{
slow = slow->next, fast = fast->next->next; // This hops the pointers correctly
if(slow == fast)
{
slow = head;
while(slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return nullptr;
}
但是當我在 for 回圈定義中宣告 change slow&fast時,狀態更改是錯誤的,程式沒有給出正確的輸出。
ListNode *detectCycle(ListNode *head) {
if(!head or !head->next)
return nullptr;
ListNode* slow, *fast;
for(slow = head, fast = head; fast && fast->next; slow = slow->next, fast=fast->next->next) // Pointers dont hop correctly
{
if(slow == fast)
{
slow = head;
while(slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return nullptr;
}
我不知道這是什么原因造成的。在我看來,在 for 回圈定義中增加指標與在 for 回圈中立即增加指標應該是一回事。有人可以深入了解為什么在回圈內遞增指標與在 for 回圈簽名中增加指標會導致不同的行為嗎?
uj5u.com熱心網友回復:
一個
for (init-statement; condition; iteration-expression)
{
dostuff();
}
映射到
{
init-statement
while ( condition )
{
dostuff();
iteration-expression ;
}
}
所以我們得到
{
slow = head, fast = head;
while (fast && fast->next)
{
slow = slow->next, fast = fast->next->next;
dostuff(); // for example purposes only. Not really replacible with a function
}
}
和
{
slow = head, fast = head;
while (fast && fast->next)
{
dostuff();
slow = slow->next, fast=fast->next->next;
}
}
在第一個,slow并且fast總是在之前更新dostuff()。
在第二種情況下,dostuff發生在slow和fast更新之前,因此在第一次回圈迭代中使用的slow和fast使用的值dostuff將不同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417782.html
標籤:
