20. 用两个栈实现队列
2023-09-14 09:01:25 时间
Question
请用栈实现一个队列,支持如下四种操作:
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
Ideas
stack的pop()无返回值
top()获取栈顶元素
Code
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> s1;
stack<int> s2;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(s1.size() > 1)
s2.push(s1.top()), s1.pop();
int x = s1.top();
s1.pop();
while(s2.size())
s1.push(s2.top()), s2.pop();
return x;
}
/** Get the front element. */
int peek() {
while(s1.size() > 1)
s2.push(s1.top()), s1.pop();
int x = s1.top();
while(s2.size())
s1.push(s2.top()), s2.pop();
return x;
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.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();
*/
相关文章
- Juc并发编程11——深入源码:常用并发容器、阻塞队列使用与原理
- rabbitmq集群搭建_rabbitmq创建队列
- MQ的作用及如何解决消息队列的丢失、重复和积压问题
- 使用单调队列解决 “滑动窗口最大值” 问题
- 发布利用Redis实现消息队列订阅发布机制(redis消息队列订阅)
- 使用PHP实现Redis队列(redis队列php)
- 优化redis队列性能:提高系统处理效率(redis队列性能)
- mysql数据库:强化数据安全与管理(mysql 数据库队列)
- 爬虫以Redis创建队列保存爬取结果(爬虫redis构建队列)
- 深入剖析MySQL的队列技术(mysql_que)
- 系统构建可靠的Redis集群版队列系统(redis集群版 队列)
- 利用Redis队列来实现数据存储的结构(redis队列存储结构)
- Redis队列记录日志保存的可靠性(redis队列保存日志)