150強訪談簡單

鍊錶循環

“鍊錶循環”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定鍊錶的頭 head,判斷鍊錶中是否有環。

如果鍊錶中存在可以透過連續跟隨下一個指標再次到達的某個節點,則鍊錶中存在循環。在內部,pos用於表示tail的next指標所連接的節點的索引。請注意,pos 不作為參數傳遞。

如果鍊錶中存在循環,則傳回 true。否則,返回 false。

輸入以值列表和整數 pos(尾部連接的索引,如果沒有循環則為 -1)的形式給出。實作函數 hasCycle(head: list, pos: int) -> bool

約束條件
  • The number of nodes in the list is in the range [0, 10000]
  • -100000 <= Node.val <= 100000
  • pos is -1 or a valid index in the linked list

範例

Example 1
Input
[3,2,0,-4], 1
Output
True
Explanation

There is a cycle: the tail node (-4) connects back to the node at index 1 (value 2).

Example 2
Input
[1,2], 0
Output
True
Explanation

There is a cycle: the tail node (2) connects back to the node at index 0 (value 1).

Example 3
Input
[1], -1
Output
False
Explanation

There is no cycle in the list.

Need a Hint?
考慮使用特定於連結清單的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。