鍊錶中環的入口節點

2021-07-27 03:35:25 字數 945 閱讀 5761

題目描述

乙個鍊錶中包含環,請找出該鍊錶的環的入口結點。

演算法描述:

受之前的面試題的啟發,如果我們在乙個有環的鍊錶中設定兩個鍊錶指標,乙個快,乙個慢,那麼兩個鍊錶指標相遇的時候,必然是位於鍊錶中的某個結點,利用這個結點,當我們從這個結點開始繼續遍歷,當再一次回到這個結點的時候,我們可以統計出環中的結點數,這個時候將兩個指標重置到煉表頭,讓其中乙個結點先走夠環的結點數,然後兩個指標同時走,當兩個結點相遇的時候,這個結點就是入口結點。

**如下:

public listnode meetingnode(listnode phead)

listnode slow = phead.next;

if (slow == null)

listnode fast = slow.next;

while (slow != null && fast != null)

slow = slow.next;

fast = fast.next;

if (fast != null)

}return

null;

}public listnode entrynodeofloop(listnode phead)

int countinloop = 1;

listnode pnode = meetingnode;

while (pnode.next != meetingnode)

pnode = phead;

for (int i = 0; i < countinloop; i++)

listnode presult = phead;

while (presult != pnode)

return presult;

}

鍊錶中環的入口節點

乙個鍊錶中包含環,請找出該鍊錶的環的入口結點。思路 通過141題,我們知道可以通過快慢指標來判斷是否有環,現在我們假設兩個指標相遇在z點,如圖 那麼我們可以知道fast指標走過a b c b slow指標走過a b 那麼2 a b a b c b 所以a c 那麼此時讓slow回到起點,fast依然...

鍊錶中環的入口節點

題目描述 乙個鍊錶中包含環,請找出該鍊錶的環的入口結點。解題思路 假設x為環前面的路程 黑色路程 a為環入口到相遇點的路程 藍色路程,假設順時針走 c為環的長度 藍色 橙色路程 第一步 找環中相匯點。分別用p1,p2指向鍊錶頭部,p1每次走一步,p2每次走二步,直到p1 p2找到在環中的相匯點。此時...

鍊錶中環的入口節點

乙個鍊錶中包含環,請找出該鍊錶的環的入口結點。struct listnode class solution listnode slow phead listnode fast phead while count while fast slow return fast listnode hasloop...