LeetCode-141 環形鏈表

  • 問題
    給定一個鏈表,判斷鏈表中是否有環。
    進階:
    你能否不使用額外空間解決此題?

  • 解答

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Solution 1
class Solution(object):
    def hasCycle(self, head):
        nodes = set([])
        cur = head
        while cur and cur.next:
            nodes.add(cur)
            cur = cur.next
            if cur in nodes:
                return True
        return False
# Solution 2 
class Solution(object):
    def hasCycle(self, head):
        fast, slow = head, head
        while fast and fast.next and slow:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return True
        return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章