原题
https://leetcode.cn/problems/linked-list-cycle/description/
思路
集合
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
seen = set()
while head:
if head in seen:
return True
seen.add(head)
head = head.next
return False
Go代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
seen := make(map[*ListNode]bool)
for head != nil {
if seen[head] {
return true
}
seen[head] = true
head = head.Next
}
return false
}
环形链表问题解析与实现
313

被折叠的 条评论
为什么被折叠?



