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

在C++中实现一个栈,核心是遵循“后进先出”(LIFO)原则。可以通过数组或链表来构建,也可以借助标准库。下面从零开始手写一个基于动态数组的栈,并说明其关键操作和设计思路。
栈的基本操作
一个完整的栈应支持以下基本操作:
push(x):将元素x压入栈顶pop():移除并返回栈顶元素top():查看栈顶元素但不删除isEmpty():判断栈是否为空size():返回栈中元素个数
使用动态数组实现栈
下面是一个简单的C++栈类实现,使用动态数组存储数据,自动扩容:
#include using namespace std;class Stack {private:int* data; // 动态数组存储元素int capacity; // 当前最大容量int topIndex; // 栈顶索引
// 扩容函数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;s.push(10);s.push(20);s.push(30);cout << "栈顶元素: " << s.top() << endl; // 输出 30s.pop();cout << "弹出后栈顶: " << s.top() << endl; // 输出 20while (!s.isEmpty()) { cout << "当前栈顶: " << s.top() << endl; s.pop();}return 0;
}
使用STL中的stack
实际开发中,可以直接使用C++标准库提供的stack:
#include #include using namespace std;int main() {stack s;s.push(1);s.push(2);s.push(3);
cout << s.top() << endl; // 输出 3s.pop();cout << s.top() << endl; // 输出 2return 0;
}
标准库的stack默认基于deque实现,也可指定为vector或list,如:stack>。
基本上就这些。手动实现有助于理解底层机制,而项目中推荐使用STL以提高效率和安全性。
以上就是C++如何实现一个栈(Stack)_C++数据结构之后进先出(LIFO)的实现的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1485321.html
微信扫一扫
支付宝扫一扫