一、题目
给定一个链表,判断链表中是否有环。
二、题解
快慢指针
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def make_list(arr):
head_node = None
p_node = None
for a in arr:
new_node = ListNode(a)
if head_node is None:
head_node = new_node
p_node = new_node
else:
p_node.next = new_node
p_node = new_node
return head_node
# def print_list(head):
# while head is not None:
# print(head.val, end=',')
# head = head.next
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow = head
fast = head
# 无环,迟早退出
while fast is not None and fast.next is not None:
slow = slow.next# 慢指针每次走一步
fast = fast.next.next# 快指针每次走两步
# 有环,迟早遇到,返回True,快指针会在环中一直转
if slow == fast:
return True
return False
s = Solution()
a = [1,2,3,4,5]
head = make_list(a)
# 使第5个结点指向第3个结点,存在环形
head.next.next.next.next.next = head.next.next
# # 无法打印,死循环
# print_list(head)
print(s.hasCycle(head))
时间复杂度:O(N),其中 N是链表中的节点数。
- 当链表中不存在环时,快指针将先于慢指针到达链表尾部,链表中每个节点至多被访问两次。
- 当链表中存在环时,每一轮移动后,快慢指针的距离将减小一。而初始距离为环的长度,因此至多移动 N轮。
空间复杂度:O(1)。我们只使用了两个指针的额外空间。