本文實例講述了Python3實現的判斷環形鏈表算法。分享給大家供大家參考,具體如下:
給定一個鏈表,判斷鏈表中是否有環。
方案一:快慢指針遍歷,若出現相等的情況,說明有環
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if fast == slow: return True return False
方案二:遍歷鏈表,尋找.next=head的元素。 但超出時間限制
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if not head: return False cur = head.next while cur: if cur.next == head: return True cur = cur.next return False
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答