当前位置:网站首页>232.用栈实现队列
232.用栈实现队列
2022-07-26 10:42:00 【Forest_1010】
class MyQueue {
public:
stack<int> stack1;
stack<int> stack2;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
int result = stack2.top();
stack2.pop();
while(!stack2.empty())
{
stack1.push(stack2.top());
stack2.pop();
}
return result;
}
/** Get the front element. */
int peek() {
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
int result=stack2.top();
while(!stack2.empty())
{
stack1.push(stack2.top());
stack2.pop();
}
return result;
}
/** Returns whether the queue is empty. */
bool empty() {
if(stack1.empty()&&stack2.empty())
return true;
else
return false;
}
};
/** * 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(); */
边栏推荐
猜你喜欢
第4期:大学生提前职业技能准备之一
putty的使用教程
[machine learning notes] [face recognition] deeplearning ai course4 4th week programming
Uniapp uses the simple method signalr (only for web debugging, cannot package apps)
$router和$route的区别
RT-Thread 学习笔记(一)---配置RT-Thread开发环境
20210807#1 C语言程序结构
Zongzi battle - guess who can win
RT thread learning notes (III) -- building a compilation environment with scons
Problems encountered in QRcode QR code (C language)
随机推荐
Redis docker instance and data structure
Redis implementation of distributed lock solution
一文详解Nodejs中fs文件模块与path路径模块
SuperMap IClient for Leaflet 加载高斯克吕格投影三度分带CGCS2000大地坐标系WMTS服务
mysql20210906
Phase 4: one of College Students' vocational skills preparation in advance
flutter 背景变灰效果,如何透明度,灰色蒙板遮罩
Problems encountered in QRcode QR code (C language)
router.push(),router.repalce(),router.go()使用
RT thread learning notes (VIII) -- start the elmfat file system based on SPI flash (Part 2)
[leetcode daily question 2021/4/29]403. Frogs cross the river
MySQL速学-2021-09-01
12 don't forget every component when copying an object
剑指Offer(二十):包含min函数的栈
[leetcode daily question 2021/2/14]765. Lovers hold hands
putty的使用教程
(转载)ArcGIS Engine中各种点的创建方法
控制随机抽中几率 [ C# | Random ]
在altium designer中禁用USBJATG
10 let operator= return a reference to *this