Top 150 Interview簡単

Linked List Cycle

Detailed guide and Python implementation for the 'Linked List Cycle' problem.

問題提起

簡単

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

The input is given as a list of values and an integer pos (the index where the tail connects to, -1 if no cycle). Implement a function 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?
Consider using Linked List-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

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 リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。