您的位置:首页 >C++实现栈结构详解
发布于2025-10-28 阅读(0)
扫一扫,手机访问
C++中栈可通过数组或链表实现,数组实现用固定大小存储和topIndex跟踪栈顶,入栈、出栈操作需检查溢出与空状态;链表实现动态分配节点,避免容量限制,通过头插法维护栈结构;标准库std::stack基于deque等容器封装,提供统一接口且更安全高效,推荐实际使用。

在C++中实现一个栈,可以通过数组或链表来完成基本的栈操作:入栈(push)、出栈(pop)、查看栈顶元素(top)以及判断是否为空(empty)。下面分别介绍两种常见的实现方式。
用固定大小的数组模拟栈结构,设置一个变量记录栈顶位置。
topIndex,初始值为-1表示空栈。data[++topIndex]。data[topIndex--]。data[topIndex](需确保非空)。示例代码:
#include <iostream> using 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; }};
链式栈动态分配内存,避免了容量限制,更适合不确定数据量的场景。
示例代码:
#include <iostream> using 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; } }};
C++ STL提供了std::stack,基于其他容器(如deque、vector)封装,使用更安全便捷。
push()、pop()、top()、empty()、size()。使用示例:
#include <stack> #include <iostream>int main() { stack<int> s; s.push(10); s.push(20); cout << s.top() << endl; // 输出 20 s.pop(); cout << s.top() << endl; // 输出 10 return 0; }
自定义实现有助于理解栈的工作原理,而实际开发中推荐使用std::stack以提高效率与安全性。基本上就这些。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8