题解 | #判断链表中是否有环#

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

# 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:
        st = set()
        if head == None: #判断是不是空list,用head==None
            return False
        # if head.val == None:
        #     return False
        while head:      #list不为空的时候,一直遍历
            l_set = len(st)
            st.add(head)
            if l_set == len(st):
                return True
            head = head.next

        return False

为head地址建立一个set,每次往里加一个,看看长度变不变

#23届找工作求助阵地#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务