题解 | #判断链表中是否有环# -- 【Python3】

判断链表中是否有环

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

1. 快慢指针

class Solution:
    def hasCycle(self , head ):
        if not head:
            return False
        slow = head;
        fast = head;
        while fast and fast.next :
            slow = slow.next
            fast = fast.next.next
            if (slow == fast):
                return True
        return False

2. 使用集合的方式

把所有的node加入到集合中,如果最后遍历出的node已经存在于集合中,则说明有环,反之则无环

class Solution:
    def hasCycle(self , head ):
        if not head:
            return False
        setCycle = set()
        while head:
            if head in setCycle:
                return True
            setCycle.add(head)
            head = head.next
        return False    
全部评论

相关推荐

嵌入式求职之路:可以看我经验😂,https://www.nowcoder.com/share/jump/73221730841876945
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务