当前位置:网站首页>LeetCode算法日记:面试题 03.04. 化栈为队
LeetCode算法日记:面试题 03.04. 化栈为队
2022-08-03 03:38:00 【happykoi】
面试题 03.04. 化栈为队
日期:2022/8/2
题目描述:实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
思路:
peek或pop的时候,用s2存储s1的逆序,这样s2的尾就是s1的首,也就是需要输出的那个元素
代码+解析:
class MyQueue {
private:
stack<int> s1;
public:
/** Initialize your data structure here. */
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() {
stack<int> temp = s1;
stack<int> s2;
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
int res = s2.top();
s2.pop();
while(s1.size() < temp.size()-1){
s1.push(s2.top());
s2.pop();
}
return res;
}
/** Get the front element. */
int peek() {
stack<int> temp = s1;
stack<int> s2;
while(!temp.empty()){
s2.push(temp.top());
temp.pop();
}
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.size() == 0;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
边栏推荐
- How to write test cases in software testing technology (2)
- vscode access denied to unins000.exe
- 肖sir___面试就业课程____性能测试
- 金仓数据库 Pro*C 迁移指南( 4. KingbaseES 的 Pro*C 迁移指南)
- 再讲Promise
- Best Practices for Migration from Jincang Database from MySQL to KingbaseES (3. MySQL Database Migration Practice)
- 硬件设计哪些事-PCB设计那些事
- PyTorch安装——安装PyTorch前在conda搭建虚拟环境的报错
- 多线程使用哈希表
- 百度超级链:鼓励企业做自己的链
猜你喜欢
随机推荐
基于Streamlit的YOLOv5ToX模型转换工具(适用YOLOv5训练出来的模型转化为任何格式)
ClickHouse uninstall and reinstall
一文了解SAP IBP是什么?
积分商城可设置的四种兑换商品类型
中非合作论坛非洲产品电商推广季启动 外交部:推动中非合作转型升级
ESP8266-Arduino编程实例-MAX6675冷端补偿K热电偶数字转换器驱动
成都高新南区 高新西区 东部新区 多边形范围点位 AOI 高德
单元测试是什么?怎么写?主要测试什么?
网工知识角|华为网络工程师,华为、华三、思科设备三层交换机如何使用三层接口?命令敲起来
金仓数据库 OCCI 迁移指南(5. 程序开发示例)
Jincang Database OCCI Migration Guide (5. Program Development Example)
path development介绍
ClickHouse删除表
道通转债,微芯转债,博22转债上市价格预测
【 original 】 Auto. Js the get and post case
Redis-Redisson介绍和用途
【无标题】2022-7-24
SeleniumWebDriver扩展插件开发
AttributeError: module ‘xxx‘ has no attribute
nVisual信息基础设施可视化管理