首先实现基于动态数组的栈类,支持push、pop、top、isEmpty和size操作,通过resize扩容;随后用main函数测试栈功能,最后介绍使用STL stack的方法。

在C++中实现一个栈,核心是遵循“后进先出”(LIFO)原则。可以通过数组或链表来构建,也可以借助标准库。下面从零开始手写一个基于动态数组的栈,并说明其关键操作和设计思路。
一个完整的栈应支持以下基本操作:
下面是一个简单的C++栈类实现,使用动态数组存储数据,自动扩容:
#include <iostream>
using namespace std;
<p>class Stack {
private:
int* data; // 动态数组存储元素
int capacity; // 当前最大容量
int topIndex; // 栈顶索引</p><pre class='brush:php;toolbar:false;'>// 扩容函数
void resize() {
capacity *= 2;
int* newData = new int[capacity];
for (int i = 0; i < topIndex; ++i) {
newData[i] = data[i];
}
delete[] data;
data = newData;
}public: // 构造函数 Stack(int initCapacity = 4) { capacity = initCapacity; data = new int[capacity]; topIndex = 0; }
// 析构函数
~Stack() {
delete[] data;
}
// 压栈
void push(int value) {
if (topIndex == capacity) {
resize();
}
data[topIndex++] = value;
}
// 弹栈
void pop() {
if (isEmpty()) {
cout << "栈为空,无法弹出元素!\n";
return;
}
--topIndex;
}
// 获取栈顶元素
int top() const {
if (isEmpty()) {
throw runtime_error("栈为空!");
}
return data[topIndex - 1];
}
// 判断是否为空
bool isEmpty() const {
return topIndex == 0;
}
// 返回元素个数
int size() const {
return topIndex;
}};
立即学习“C++免费学习笔记(深入)”;
写一个简单的main函数验证栈的行为:
int main() {
Stack s;
<pre class='brush:php;toolbar:false;'>s.push(10);
s.push(20);
s.push(30);
cout << "栈顶元素: " << s.top() << endl; // 输出 30
s.pop();
cout << "弹出后栈顶: " << s.top() << endl; // 输出 20
while (!s.isEmpty()) {
cout << "当前栈顶: " << s.top() << endl;
s.pop();
}
return 0;}
实际开发中,可以直接使用C++标准库提供的stack:
#include <stack>
#include <iostream>
using namespace std;
<p>int main() {
stack<int> s;
s.push(1);
s.push(2);
s.push(3);</p><pre class='brush:php;toolbar:false;'>cout << s.top() << endl; // 输出 3
s.pop();
cout << s.top() << endl; // 输出 2
return 0;}
标准库的stack默认基于deque实现,也可指定为vector或list,如:stack<int, vector<int>>。
基本上就这些。手动实现有助于理解底层机制,而项目中推荐使用STL以提高效率和安全性。
以上就是C++如何实现一个栈(Stack)_C++数据结构之后进先出(LIFO)的实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号