LeetCode 141 环形链表 python

题目描述

给定一个链表,判断链表中是否有环。

样例

如果有环 返回True
否则 返回False

想法一: 遍历链表,将遍历过的节点加入list,如果出现重复节点,则返回True,否则遍历结束,返回False,但是结果超时。

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

想法二: 创建两个节点,第一个慢节点单步走,第二个快节点两步走,如果没有环,则快节点会首先走到链表尾,退出循环,返回False。如果存在环,则快节点会再第二圈或者第三圈的地方追上慢节点,直到两者相等,则返回True。

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        # 空或者单一个的时候
        if head == None or head.next == None:
            return False

        first = second = head
        while second and second.next:
            first = first.next
            second = second.next.next
            if first == second:
                return True
        return False

最后

刷过的LeetCode源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063

原文地址:https://www.cnblogs.com/GF66/p/9785470.html