LeetCode

141. 环形链表

2019-03-30  本文已影响0人  cptn3m0
# 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
        """
        fast = head
        slow = head
        
        while fast is not None:
            slow = slow.next
            fast = fast.next
            
            # check 是否链表最后
            # 这一步必须检查, 如果不检查, 就会出现在`None`上调用 next 的操作
            if fast == None:
                return False
            # 再走一步
            fast = fast.next
            # 走两步看看情况
            if fast == slow:
                return True
            
        return False
            
上一篇 下一篇

猜你喜欢

热点阅读