本文最后更新于13 天前,其中的信息可能已经过时,如有错误请发送邮件到big_fw@foxmail.com
📋 1. 使用 C++ STL 标准库(最常用)
这是开发中最推荐的方式,直接用标准库封装好的 std::stack 和 std::queue。
#include <iostream>
#include <stack> // 栈头文件
#include <queue> // 队列头文件
using namespace std;
int main() {
// ========== 栈(stack)操作 ==========
stack<int> s;
s.push(10); // 压入元素
s.push(20);
s.push(30);
cout << "栈顶元素: " << s.top() << endl; // 获取栈顶(30)
s.pop(); // 弹出栈顶(30被移除)
cout << "弹出后栈顶: " << s.top() << endl; // 20
cout << "栈是否为空: " << (s.empty() ? "是" : "否") << endl;
cout << "栈的大小: " << s.size() << endl;
// ========== 队列(queue)操作 ==========
queue<int> q;
q.push(100); // 入队
q.push(200);
q.push(300);
cout << "\n队头元素: " << q.front() << endl; // 获取队头(100)
q.pop(); // 出队(100被移除)
cout << "出队后队头: " << q.front() << endl; // 200
cout << "队列是否为空: " << (q.empty() ? "是" : "否") << endl;
cout << "队列的大小: " << q.size() << endl;
return 0;
}
🛠️ 2. 自定义 C++ 类实现栈和队列
如果你想自己封装一个类来理解底层实现,这里用动态数组实现栈,用链表实现队列。
#include <iostream>
#include <cstdlib> // 用于内存分配
using namespace std;
// 自定义栈类
class MyStack {
private:
int *data;
int top;
int capacity;
void resize() {
capacity *= 2;
int *new_data = new int[capacity];
for (int i = 0; i <= top; ++i)
new_data[i] = data[i];
delete[] data;
data = new_data;
}
public:
MyStack(int cap = 4) : capacity(cap), top(-1) {
data = new int[capacity];
}
~MyStack() { delete[] data; }
void push(int val) {
if (top == capacity - 1) resize();
data[++top] = val;
}
void pop() {
if (empty()) {
cerr << "栈空,无法弹出!" << endl;
return;
}
top--;
}
int getTop() {
if (empty()) {
cerr << "栈空,无栈顶元素!" << endl;
return -1;
}
return data[top];
}
bool empty() { return top == -1; }
int size() { return top + 1; }
};
// 自定义队列类(链表实现)
class Node {
public:
int val;
Node *next;
Node(int v) : val(v), next(nullptr) {}
};
class MyQueue {
private:
Node *frontNode;
Node *rearNode;
int count;
public:
MyQueue() : frontNode(nullptr), rearNode(nullptr), count(0) {}
~MyQueue() {
while (frontNode) {
Node *temp = frontNode;
frontNode = frontNode->next;
delete temp;
}
}
void enqueue(int val) {
Node *newNode = new Node(val);
if (empty()) {
frontNode = rearNode = newNode;
} else {
rearNode->next = newNode;
rearNode = newNode;
}
count++;
}
void dequeue() {
if (empty()) {
cerr << "队列空,无法出队!" << endl;
return;
}
Node *temp = frontNode;
frontNode = frontNode->next;
delete temp;
count--;
if (empty()) rearNode = nullptr;
}
int getFront() {
if (empty()) {
cerr << "队列空,无队头元素!" << endl;
return -1;
}
return frontNode->val;
}
bool empty() { return count == 0; }
int size() { return count; }
};
// 测试自定义栈和队列
int main() {
MyStack s;
s.push(10);
s.push(20);
cout << "自定义栈顶: " << s.getTop() << endl; // 20
s.pop();
cout << "弹出后栈顶: " << s.getTop() << endl; // 10
MyQueue q;
q.enqueue(100);
q.enqueue(200);
cout << "\n自定义队头: " << q.getFront() << endl; // 100
q.dequeue();
cout << "出队后队头: " << q.getFront() << endl; // 200
return 0;
}
💡 关键区别
- STL 版本:直接调用
s.push()、s.pop()等成员函数,底层实现已经优化,开发效率高。 - 自定义版本:自己管理内存和指针,适合理解底层原理,面试时可能会要求手写。

