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

在C++中实现一个栈,可以通过数组或链表来完成基本的栈操作:入栈(push)、出栈(pop)、查看栈顶元素(top)以及判断是否为空(empty)。下面分别介绍两种常见的实现方式。
用固定大小的数组模拟栈结构,设置一个变量记录栈顶位置。
topIndex,初始值为-1表示空栈。data[++topIndex]。data[topIndex--]。data[topIndex](需确保非空)。示例代码:
#include <iostream>
using namespace std;
<p>class Stack {
private:
int data[100];
int topIndex;</p><p>public:
Stack() : topIndex(-1) {}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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++免费学习笔记(深入)”;
示例代码:
#include <iostream>
using namespace std;
<p>struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};</p><p>class LinkedStack {
private:
Node* topNode;</p><p>public:
LinkedStack() : topNode(nullptr) {}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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>
<p>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以提高效率与安全性。基本上就这些。
以上就是c++++怎么实现一个栈(stack)_c++栈结构实现方法解析的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                
                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号