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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。