鍊錶中與環相關的問題

2021-07-22 17:27:59 字數 1164 閱讀 4262

141. linked list cycle

given a linked list, determine if it has a cycle in it.

follow up:

can you solve it without using extra space?

subscribe to see which companies asked this question

題目鏈結

利用乙個快指標,乙個慢指標。如果它們能相遇,則存在環。

/**

* language: cpp ( 9ms )

* definition for singly-linked list.

* struct listnode

* };

*/class solution

listnode* fast=head,*slow=head->next;

while(fast!=slow)else

}return true;

}};

142. linked list cycle ii

given a linked list, return the node where the cycle begins. if there is no cycle, return null.

note: do not modify the linked list.

follow up:

can you solve it without using extra space?

題目鏈結

判斷環的入口點 :相遇點到環入口的距離等於頭節點到環入口的距離。

class solution 

listnode *slow=head,*fast=head;

while(fast!=null&&fast->next!=null)

}if(fast!=slow)

slow=head;

while(fast!=slow)

return fast;

}};

計算環的長度

如何判斷兩個鍊錶(不帶環)是否相交

資料參考

鍊錶系列 鍊錶環相關問題

設定兩個節點 slow fast,若存在環,分別從鍊錶的頭節點出發,乙個每次向後移動一步,另乙個移動兩步,兩個指標移動速度不一樣,如果存在環,那麼兩個指標一定會在環裡相遇。public boolean hascircle node head node slow head node fast head...

鍊錶環相關演算法問題

這些演算法問題網上有很多講解的,因為要設計到一些數學的邏輯推算問題,所以看了很多剛開始真是沒動整個推演過程是什麼樣子的,活生生從早 上6點搞到下午有時間就想一下,沒想上了趟廁所回來就知道怎麼回事了,記錄一下,以防再次忘記。另乙個要掌握的理由就是這都是特別經典的 演算法題,雖然不用但是面試還是會常常被...

鍊錶環問題

給定乙個鍊錶,判斷該鍊錶中是否有環?如果有的話,環的長度是多少?環的入口是哪個節點?使用快慢指標策略,兩個指標都從頭指標出發,快指標每次走兩步,慢指標每次走一步。1.判斷鍊錶是否有環?如果快慢節點相遇,那麼鍊錶有環。2.如果有環,環的長度是多少?快慢指標相遇後,固定其中乙個指標 如快指標 不動,另乙...