什么是 stack(栈)?
想象一下你有一把ak,你给ak上膛子弹,最后上膛的子弹先发射出去。这种"后进先出"的结构就是栈。
常用操作:
-
push(x)
:把元素x
压入栈顶。 -
pop()
:移除栈顶元素(但不返回值)。 -
top()
:查看栈顶元素的值。 -
empty()
:判断栈是否为空。 -
size()
:返回栈中元素个数。cs#include <iostream> #include <stack> using namespace std; int main() { stack<int> s; s.push(10); s.push(20); s.push(30); cout << s.top() << endl; // 输出: 30 s.pop(); cout << s.top() << endl; // 输出: 20 return 0; }
什么是 queue(队列)?
想象你在排队买奶茶,新来的人要排在队尾 ,而服务员从队首 开始服务。这种"先进先出"的结构就是队列。
常用操作:
-
push(x)
:把元素x
加入队尾。 -
pop()
:移除队首元素。 -
front()
:查看队首元素。 -
back()
:查看队尾元素。 -
empty()
和size()
:和 stack 一样。cpp#include <iostream> #include <queue> using namespace std; int main() { queue<string> q; q.push("Alice"); q.push("Bob"); q.push("Charlie"); cout << q.front() << endl; // 输出: Alice q.pop(); cout << q.front() << endl; // 输出: Bob return 0; }
总结对比
操作 stack(栈) queue(队列) 添加元素 push(x)
push(x)
删除元素 pop()
(栈顶)pop()
(队首)查看元素 top()
front()
/back()
顺序 后进先出 先进先出
使用场景
- stack:括号匹配、函数调用栈、撤销操作
- queue:任务调度、BFS(广度优先搜索)、打印任务队列
- 记住头文件:
#include <stack>
和#include <queue>
。 pop()
只删除,不返回值,要用top()
或front()
先看值。- 别忘了检查
empty()
,否则访问空容器会出错!