一、题目
二、代码
class MyQueue {
public:
stack<int> stack_true; //真实用于模拟队列的堆栈 这个堆栈从顶向下应该就是队列的头到尾
stack<int> stack_help; //辅助堆栈
int first_num=0;
MyQueue() {
}
void push(int x) {
while(!stack_true.empty()) //当模拟堆栈不为空的时候 一个一个都压入到help中
{
stack_help.push(stack_true.top());
stack_true.pop();
}
stack_true.push(x); //把新的数值放在最底下
while(!stack_help.empty()) // 再把数值装回去
{
stack_true.push(stack_help.top());
stack_help.pop();
}
}
int pop() {
first_num= stack_true.top(); //取出该数值
stack_true.pop(); //将其从堆栈中移除
return first_num;
}
int peek() {
return stack_true.top();
}
bool empty() {
return stack_true.empty();
}
};
/**
* 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();
*/