-
問題
給定一個鏈表,判斷鏈表中是否有環。
進階:
你能否不使用額外空間解決此題? -
解答
# 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