[LintCode 102] 帶環鏈表(Python)

題目描述

給定一個鏈表,判斷它是否有環。

樣例
給出 -21->10->4->5, tail connects to node index 1,返回 true

思路

快慢針。快針每次都兩步,慢針每次走一步。如果無環,快針肯定會率先到達隊尾,即遇到None。如果有環,快針永遠無法遇到None,並且會與慢針相遇。

代碼

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param head: The first node of the linked list.
    @return: True if it has a cycle, or false
    """
    def hasCycle(self, head):
        # write your code here
        if head is None:
            return False
        f = head
        s = head
        while f.next is not None and f.next.next is not None:
            f = f.next.next
            s = s.next
            if s == f:
                return True
        return False

複雜度分析

時間複雜度O(n) ,空間複雜度O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章