C++中栈可通过数组或链表实现,数组实现用固定大小存储和topIndex跟踪栈顶,入栈、出栈操作需检查溢出与空状态;链表实现动态分配节点,避免容量限制,通过头插法维护栈结构;标准库std::stack基于deque等容器封装,提供统一接口且更安全高效,推荐实际使用。

在C++中实现一个栈,可以通过数组或链表来完成基本的栈操作:入栈(push)、出栈(pop)、查看栈顶元素(top)以及判断是否为空(empty)。下面分别介绍两种常见的实现方式。
使用数组实现栈
用固定大小的数组模拟栈结构,设置一个变量记录栈顶位置。
- 定义一个数组和一个整型变量
topIndex,初始值为-1表示空栈。 - 入栈时先检查是否溢出,然后将元素放入
data[++topIndex]。 - 出栈时检查是否为空,再返回
data[topIndex--]。 - 获取栈顶直接返回
data[topIndex](需确保非空)。
示例代码:
#includeusing namespace std; class Stack { private: int data[100]; int topIndex;
public: Stack() : topIndex(-1) {}
void push(int value) { if (topIndex >= 99) { cout << "栈溢出!" << endl; return; } data[++topIndex] = value; } void pop() { if (topIndex < 0) { cout << "栈为空!" << endl; return; } topIndex--; } int peek() const { if (topIndex < 0) { throw runtime_error("栈为空!"); } return data[topIndex]; } bool empty() const { return topIndex == -1; }};
使用链表实现栈
链式栈动态分配内存,避免了容量限制,更适合不确定数据量的场景。
立即学习“C++免费学习笔记(深入)”;
- 每个节点包含数据和指向下一个节点的指针。
- 栈顶指针始终指向当前最上层元素。
- 入栈即创建新节点并插入到头部。
- 出栈删除头节点并释放内存。
示例代码:
#includeusing namespace std; struct Node { int data; Node* next; Node(int val) : data(val), next(nullptr) {} };
class LinkedStack { private: Node* topNode;
public: LinkedStack() : topNode(nullptr) {}
void push(int value) { Node* newNode = new Node(value); newNode->next = topNode; topNode = newNode; } void pop() { if (!topNode) { cout << "栈为空!" << endl; return; } Node* temp = topNode; topNode = topNode->next; delete temp; } int top() const { if (!topNode) { throw runtime_error("栈为空!"); } return topNode->data; } bool empty() const { return topNode == nullptr; } ~LinkedStack() { while (topNode) { Node* temp = topNode; topNode = topNode->next; delete temp; } }};
标准库中的栈(std::stack)
C++ STL提供了
std::stack,基于其他容器(如deque、vector)封装,使用更安全便捷。
- 包含在
头文件中。 - 默认底层容器是deque。
- 提供一致的接口:
push()、pop()、top()、empty()、size()。使用示例:
#include#include int main() { stack
s; s.push(10); s.push(20); cout << s.top() << endl; // 输出 20 s.pop(); cout << s.top() << endl; // 输出 10 return 0; } 自定义实现有助于理解栈的工作原理,而实际开发中推荐使用
std::stack以提高效率与安全性。基本上就这些。











