呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

leetcode 141 Linked List Cycle

文档信息

leetcode 141 Linked List Cycle

解法一

解法二

# 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 head == None or head.next == None:
            return False # 有0个或1个元素的链表不可能出现环
        
        slow = head
        fast = head.next
        while fast != slow:
            if fast == None or fast.next == None: # fast指针到达链表尾,则没有环
                return False
            slow = slow.next
            fast = fast.next.next
            
        return True # fast指针追上slow指针,证明有环

note

捐赠支持

可以使用支付宝转帐给richard.ma.19850509#gmail.com(请将#替换为@),谢谢!

Fork me on GitHub