判断链表是否为循环链表。两种思路,一是使用哈希表;二是使用快慢指针
哈希表:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not(head and head.next):
return False
a =set()
while head:
if head in a:
return True
a.add(head)
head = head.next
return False
快慢指针法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not (head and head.next):
return False
slow , fast = head ,head
while fast and fast.next: #fast 如果走到none,则无环,否则一直循环,有环
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
时间复杂度O(n),空间复杂度O(1)