141. 环形链表






方法一思路:

快慢指针。

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast == slow:
                return True
        return False

方法二思路:

用list或set。

class Solution(object):
    def hasCycle2(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        list = []
        while head:
            if head in list:
                return True
            list.append(head)
            head = head.next
        return False
posted @ 2020-05-09 14:11  人间烟火地三鲜  阅读(163)  评论(0编辑  收藏  举报