当前位置:网站首页>用两个栈实现一个队列。
用两个栈实现一个队列。
2022-07-22 18:08:00 【yn20000227】
队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
class CQueue {
private:
stack<int> instack;
stack<int> outstack;/*一个作为输入栈,一个作为输出栈*/
public:
CQueue() {
}
void appendTail(int value) {
instack.push(value);
}
int deleteHead() {
if(!outstack.empty()){
int value = outstack.top();
outstack.pop();
return value;
}
else{
while(!instack.empty()){
int top = instack.top();
instack.pop();
outstack.push(top);
}
if(outstack.empty()){
return -1;
}else{
int output = outstack.top();
outstack.pop();
return output;
}
}
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
边栏推荐
猜你喜欢
随机推荐
Greatest common divisor and least common multiple
RPC-BDY(1)-一个最简单RPC实现
Code random notes_ Linked list_ 206 reverse linked list
Freshman summer internship Day5_ one
"Dial" out the number on the number of digits - a variety of ideas to achieve reverse output of a four digit number
Programming Xiaobai's first blog
Debug No2 按流程检查错误
App自动化测试是怎么实现H5测试的
Form validation and regular expressions (I)
编程小白的第一篇博客
Vrtk reactivates the scene, jumps to the scene handle, and the UI interaction function is lost
Common tools and resources
VRTK重新激活场景 跳转场景 手柄UI交互功能丢失问题
Pointers and functions
leetcode
动态规划A-1
Unity创建FPS监视
Fundamentals of C language - the most error prone test point of string / character array
Get computer hardware information
Debug No4 利用RenderDoc排查bug









