当前位置:网站首页>20. 用两个栈实现队列
20. 用两个栈实现队列
2022-08-02 02:20:00 【Hunter_Kevin】
题目
请用栈实现一个队列,支持如下四种操作:
push(x) – 将元素x插到队尾;
pop() – 将队首的元素弹出,并返回该元素;
peek() – 返回队首元素;
empty() – 返回队列是否为空;
注意:
你只能使用栈的标准操作:push to top,peek/pop from top, size 和 is empty;
如果你选择的编程语言没有栈的标准库,你可以使用list或者deque等模拟栈的操作;
输入数据保证合法,例如,在队列为空时,不会进行pop或者peek等操作;
数据范围
每组数据操作命令数量 [0,100]。
样例
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
代码
维护两个栈,一个栈存储数据,另一个栈作为中转栈,满足队列的top、pop等操作
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> a, b;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
a.push(x);
}
void copy(stack<int> &x, stack<int> &y){
while(x.size()){
y.push(x.top());
x.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
copy(a,b);
int res = b.top();
b.pop();
copy(b,a);
return res;
}
/** Get the front element. */
int peek() {
copy(a,b);
int res = b.top();
copy(b,a);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return a.empty();
}
};
/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * bool param_4 = obj.empty(); */
边栏推荐
- Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
- 软件测试 接口自动化测试 pytest框架封装 requests库 封装统一请求和多个基础路径处理 接口关联封装 测试用例写在yaml文件中 数据热加载(动态参数) 断言
- 【LeetCode每日一题】——704.二分查找
- Check if IP or port is blocked
- FOFAHUB usage test
- 2023年起,这些地区软考成绩低于45分也能拿证
- 使用DBeaver进行mysql数据备份与恢复
- LeetCode刷题日记: 33、搜索旋转排序数组
- Speed up your programs with bitwise operations
- 局部敏感哈希:如何在常数时间内搜索Embedding最近邻
猜你喜欢

项目后台技术Express

菜刀webshell特征分析

2023年起,这些地区软考成绩低于45分也能拿证

How engineers treat open source

【LeetCode每日一题】——103.二叉树的锯齿形层序遍历

Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒

Use DBeaver for mysql data backup and recovery

Install mysql using docker

Unable to log in to the Westward Journey

Win Go development kit installation configuration, GoLand configuration
随机推荐
BI-SQL丨WHILE
AWR分析报告问题求助:SQL如何可以从哪几个方面优化?
Outsourcing worked for three years, it was abolished...
C language inserted into the characters of simple exercises
优炫数据库导库导错了能恢复吗?
Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles
leetcode/字符串中的变位词-s1字符串的某个排列是s2的子串
LeetCode Brushing Diary: 74. Searching 2D Matrix
2022-07-30 mysql8执行慢SQL-Q17分析
Handwriting a blogging platform ~ the first day
TKU remembers a single-point QPS optimization (I wish ITEYE is finally back)
通用客户端架构
NAS和私有云盘的区别?1篇文章说清楚
"NetEase Internship" Weekly Diary (1)
MySQL optimization strategy
BI - SQL 丨 WHILE
AOF rewrite
接口测试神器Apifox究竟有多香?
Fundamentals of Cryptography: X.690 and Corresponding BER CER DER Encodings
2022年NPDP考完多久出成绩?怎么查询?