基本概念
栈是一种只允许在一端进行操作的线性表。具体地说,栈是一种特殊的线性表,只允许在栈顶进行操作,而栈底不允许操作。
由于仅容许在一端操作,使其具有后进先出的结构特性。
常见的栈操作包括:
创建栈、销毁栈、清空栈、入栈、出栈、获取栈顶元素、获取栈的大小等。例如,在C++中,对栈的介绍如下:
std::stack
template <class T, class Container = deque<T> > class stack;
LIFO stack Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container.
stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.
The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:
empty size back push_back pop_back
The standard container classes vector, deque and list fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container deque is used.
简单示例
#include <stack>
#include <iostream>
using namespace std;
int main()
{
stack<int> test_stack;
cout << test_stack.empty() << endl;
cout << test_stack.size() << endl;
for (size_t i = 0; i < 5; ++i)
{
test_stack.push(i);
}
cout << test_stack.top() << endl;
test_stack.pop();
cout << test_stack.top() << endl;
return 0;
}
实现
实现栈时,可以采用数组和链表作为栈的存储结构。
我们需要:
保存当前栈顶位置栈顶标识;
栈的最大容量及存储空间;
栈当前大小。
入栈时判断栈是否满;
出栈时判断栈是否为空;
获取栈顶元素时判断栈是否为空;