Leetcode练习(Python):链表类:第141题:环形链表:给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

题目:
环形链表:给定一个链表,判断链表中是否有环。  为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。  
思路:
双指针
程序:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head:
            return None
        if not head.next:
            return None
        index1 = head
        index2 = head
        while index2 and index2.next:
            index2 = index2.next.next
            index1 = index1.next
            if index1 == index2:
                return True
        return False

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12813399.html