【leetcode】环形链表(python实现)

题目详情:
给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

在这里插入图片描述
做的时候,想到可以遍历每一个节点存储到一个列表,与此同时再进行判断当前节点是否再列表当中,如果在列表当中,返回True,否则的话就返回False

代码:

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        listNode = []
        if head:
            return False
        
        while head and head.next:
            if head not in listNode:
                listNode.append(head)
                head = head.next
            else:
                return True
        return False

但是。。呃 运行时间居然是2700+ms,实在是太天真了。

还有另外两种方法是参考别人的,运行时间都在60ms左右【太神奇了】:

1.通过字典遍历,其实跟我们刚刚的思路差不多,就是一个用列表一个用字典:

d = dict()
        cur = head
        while cur:
            if cur in d:
                return True
            d[cur] = 1
            cur = cur.next
        return False

2.通过快慢指针。
思路:因为如果存在环状链表,那么head就一定有head.next,这样的话就可以定义两个指针,慢指针走一步的同时,快指针就走两步,当快指针走到链表尾了没有下一个节点了的时候,那么就说明不存在环状指针
代码:

slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

谢谢观看!

猜你喜欢

转载自blog.csdn.net/qq_43538596/article/details/88967032