题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
思路很简单,用一个set保存下链表节点的引用,在链表遍历的过程中,如果某个节点的引用在set中存在,说明该链表有环
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return bool布尔型
#
class Solution:
def hasCycle(self , head: ListNode) -> bool:
refSet = set()
p = head
while p != None:
if p in refSet:
return True
refSet.add(p)
p = p.next
return False