简体   繁体   English

如果用链表实现堆栈,堆栈的大小函数的时间复杂度如何?

[英]How Is the time complexity of size function of stack constant if stack is implemented by linked list?

At Any point of time if we invoke size function it means to calculate size we need to traverse whole linked list which is O(n).在任何时候,如果我们调用 size 函数,这意味着计算我们需要遍历整个链表的大小,即 O(n)。 I want to know about the standard template library c++ size function.. The only way to get O(1) is to keep a track of push and pop operations ?我想了解标准模板库 c++ 大小函数.. 获得 O(1) 的唯一方法是跟踪推送和弹出操作? is it how it is done in c++ standard library?它是如何在 C++ 标准库中完成的?

You don't necessarily need to traverse a list to know its size.您不一定需要遍历列表来了解其大小。 As long as you keep the size as a member variable of the class and correctly increment/decrement it when the size of the list changes, returning the size() is a O(1) operation.只要您将 size 作为类的成员变量,并在列表的size()发生变化时正确地递增/递减它,返回size()就是一个 O(1) 操作。 The size() member function can be implemented as simply size_t size() const noexcept { return m_size; } size()成员函数可以简单地实现为size_t size() const noexcept { return m_size; } size_t size() const noexcept { return m_size; } or similar. size_t size() const noexcept { return m_size; }或类似的。

According to the container requirements (C++ 17, 26.2.1 General container requirements) if a container has member function size then its complexity is constant.根据容器要求(C++ 17, 26.2.1 一般容器要求),如果容器具有成员函数大小,则其复杂度是恒定的。 And the standard container std::list has the member function size.标准容器std::list具有成员函数大小。

And the member function of the standard container adapter std::stack is defined like标准容器适配器std::stack的成员函数定义如下

size_type size() const { return c.size(); }

where c is the underlined container as for example std::list .其中c是带下划线的容器,例如std::list So it also has the constant complexity.所以它也有恒定的复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM