Stack
Introduction
A stack is a commonly used linear data structure in OI. Please note that this article primarily discusses the stack data structure, not the system stack/stack space during program execution.
Modifications and access to a stack follow the Last-In-First-Out principle, hence a stack is often referred to as a Last-In-First-Out (LIFO) list.
Warning
LIFO describes that the currently last element in the container is the first to be removed.
Consider the following stack operations:
1 2 3 4 | |
If considered as a whole, 1 is pushed first and popped first, 2 is pushed last and popped last, which would make it a First-In-First-Out list—clearly incorrect.
Therefore, when determining whether a data structure is LIFO or FIFO, one should consider the state within the current container.
Simulating a Stack Using an Array
We can conveniently simulate a stack using an array, as shown below:
Implementation
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Stack in C++ STL
The C++ STL also provides a container std::stack. Include the <stack> header to use it.
STL Definition of stack
1 2 3 4 5 | |
T is the data type to be stored in the stack.
Container is the underlying container type used to store elements. This container must provide the following functions with their usual semantics:
back()push_back()pop_back()
STL containers std::vector, std::deque, and std::list satisfy these requirements. If not specified, std::deque is used as the default underlying container.
The stack container in STL provides a set of member functions for use. The more commonly used ones are:
- Element Access
st.top()returns the top element of the stack.
- Modifiers
st.push()inserts the passed argument onto the top of the stack.st.pop()removes the top element from the stack.
- Capacity
st.empty()returns whether the stack is empty.st.size()returns the number of elements.
Additionally, std::stack provides some operators. The most commonly used is the assignment operator = to assign one stack to another. Example:
1 2 3 4 5 6 7 8 9 10 11 12 | |
Simulating a Stack Using Python's List
In Python, you can use a list to simulate a stack:
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
References
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用