-
问题
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题? -
解答
# 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