【剑指Offer系列09】用两个栈实现队列
题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
代码
Python
class CQueue:
def __init__(self):
# A存储, B辅助
self.A, self.B = [], []
def appendTail(self, value: int) -> None:
self.A.append(value)
def deleteHead(self) -> int:
# B非空
if self.B: return self.B.pop()
# A为空
if not self.A: return -1
# A非空
while self.A:
self.B.append(self.A.pop())
return self.B.pop()
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
C++
class CQueue {
public:
// A存储, B辅助
stack<int> A;
stack<int> B;
CQueue() {}
void appendTail(int value) {
A.push(value);
}
int deleteHead() {
// A为空
if (A.empty()) return -1;
// A非空
while (!A.empty()) {
int tmp1=A.top();
A.pop();
B.push(tmp1);
}
int res=B.top();
B.pop();
// B非空
while (!B.empty()) {
int tmp2=B.top();
B.pop();
A.push(tmp2);
}
return res;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/