1. 程式人生 > >LeetCode題目--環形連結串列(python實現)

LeetCode題目--環形連結串列(python實現)

題目

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

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

 

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
        """
        slow = fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False