1. 程式人生 > >17.環形連結串列-Leetcode 141(python)

17.環形連結串列-Leetcode 141(python)

  • 題目描述

給定一個連結串列,判斷連結串列中是否有環。

進階: 你能否不使用額外空間解決此題?

  • 解決思路

自己想不出解決的思路,參照網友的解決方案,實在是非常巧妙,定義快慢指標,考慮如果連結串列中有環,那麼快指標一定會追上慢指標。

  • 程式碼
# 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
        #定義快慢指標
        fast = slow = head
        #快指標走得快,如果沒有環的話,一定會先走到末尾的空指標處
        while fast and fast.next:
            #慢指標一次走一步
            slow = slow.next
            #快指標一次走兩步(因為我們已經判斷過一步後的節點不是空了,不用擔心會報Node沒有next屬性的錯誤)
            fast = fast.next.next
            #如果快指標能夠追上慢指標,就說明連結串列有環
            if fast == slow:
                return True
        
        return False