双栈实现队列
程序员文章站
2024-03-18 18:07:28
...
class CQueue {
public:
stack<int> s1;
stack<int> s2;
CQueue() {
while(!s1.empty()) s1.pop();
while(!s2.empty()) s2.pop();
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() { //只有s2空的时候才把s1的东西倒腾过去
//不需要每次都来回倒腾
if(s2.empty()){
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
if(s2.empty()) return -1;
int temp = s2.top();
s2.pop();
return temp;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
上一篇: C++文件输入输出