[英]while reversing the singly linked list using recursion why is the space complexity o(1) when we are using the stack space inside the memory
在使用递归反转单链表时,为什么当我们使用 memory 内部的堆栈空间时空间复杂度为 o(1)
def reverse(self,head):
if(head==None or head.next==None):
return head
res=self.reverse(head.next)
head.next.next=head
head.next=None
return res
大 O 复杂度对于时间和空间都不是非常精确的度量。 它只是说明当输入元素的数量增加时算法将如何表现。
你是对的,堆栈使用将是线性的(所以 O(n)),但那部分与元素的大小无关。 Furthermore in Python, even if the stack uses memory it is handled specially, and the maximum recursion depth is controlled by sys.getrecursionlimit
and sys.setrecursionlimit
and it uses a dedicated memory array, in the sense that it is reserved whether you use it or不是。 出于这个原因,当我们谈到空间复杂度时,通常不会考虑堆栈的使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.