题目描述:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
[“CQueue”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
[“CQueue”,“deleteHead”,“appendTail”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
思路:
首先应该明白队列是“先进先出”。栈是“先进后出”。所以一个栈用来模拟队列入列,一个栈用来模拟队列出列。两个栈分别为stack1和stack2,入列时,数据入栈stack1;出列时,判断是否stack2是否为空,不为空直接出栈;否则看stack1是否为空,不为空将stack1中数入栈stack2。两个皆为空输出-1。
class CQueue {
public:
stack <int> stack1;
stack <int> stack2;
CQueue() {
}
void appendTail(int value) {
stack1.push(value);
}
int deleteHead() {
int res=-1;
//sta2不为空,直接pop
if (stack2.size() > 0) {
res = stack2.top();
stack2.pop();
}
//sta2为空,且有元素push时,元素push进sta2
else if (stack1.size() > 0) {
while (stack1.size() > 0) {
int ele = stack1.top();
stack1.pop();
stack2.push(ele);
}
res = stack2.top();
stack2.pop();
}
return res;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/