這篇文章給大家分享的是有關(guān)Python3怎么實(shí)現(xiàn)判斷環(huán)形鏈表算法的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
具體如下:
給定一個(gè)鏈表,判斷鏈表中是否有環(huán)。
方案一:快慢指針遍歷,若出現(xiàn)相等的情況,說明有環(huán)
# 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 """ slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if fast == slow: return True return False
方案二:遍歷鏈表,尋找.next=head的元素。 但超出時(shí)間限制
# 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 not head: return False cur = head.next while cur: if cur.next == head: return True cur = cur.next return False
感謝各位的閱讀!關(guān)于“Python3怎么實(shí)現(xiàn)判斷環(huán)形鏈表算法”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!