美文网首页
leetcode 141 python 环形链表

leetcode 141 python 环形链表

作者: 慧鑫coming | 来源:发表于2019-01-31 09:15 被阅读0次

传送门

题目要求

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

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

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

141-1

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

141-2

示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

141-3

思路一

用两个节点遍历链表,一快一慢,若快慢节点能相遇,证明链表中存在环

→_→ talk is cheap, show me the code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

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

相关文章

网友评论

      本文标题:leetcode 141 python 环形链表

      本文链接:https://www.haomeiwen.com/subject/zixksqtx.html