当前位置:网站首页>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(); */
边栏推荐
- 【 wheeled odometer 】
- Hiring a WordPress Developer: 4 Practical Ways
- "NetEase Internship" Weekly Diary (2)
- Coding Experience Talk
- LeetCode brushing diary: 53, the largest sub-array and
- Force buckle, 752-open turntable lock
- 2022-07-30 mysql8执行慢SQL-Q17分析
- LeetCode Brushing Diary: 74. Searching 2D Matrix
- swift项目,sqlcipher3 -&gt; 4,无法打开旧版数据库有办法解决吗
- LeetCode刷题日记:153、寻找旋转排序数组中的最小值
猜你喜欢
随机推荐
oracle查询扫描全表和走索引
libcurl访问url保存为文件的简单示例
TKU remembers a single-point QPS optimization (I wish ITEYE is finally back)
软件测试 接口自动化测试 pytest框架封装 requests库 封装统一请求和多个基础路径处理 接口关联封装 测试用例写在yaml文件中 数据热加载(动态参数) 断言
Golang分布式应用之Redis
The state status is displayed incorrectly after the openGauss switch
AWR analysis report questions for help: How can SQL be optimized from what aspects?
Win Go development kit installation configuration, GoLand configuration
Nanoprobes纳米探针丨Nanogold偶联物的特点和应用
The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
2022年NPDP考完多久出成绩?怎么查询?
The underlying data structure of Redis
MySQL优化策略
ofstream,ifstream,fstream read and write files
messy website
2022-07-30 mysql8 executes slow SQL-Q17 analysis
Data transfer at the data link layer
LeetCode刷题日记:LCP 03.机器人大冒险
Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案
Chengdu openGauss user group recruit!








![[ORB_SLAM2] void Frame::ComputeImageBounds(const cv::Mat & imLeft)](/img/ed/ffced88c9d23c20ccf380494051381.jpg)
