题目类型:用栈实现队列
class MyQueue {
private:
stack<int> que_stack;
stack<int> com_stack;
public:
void push(int x) {
//que_stack为空的话,将com_stack中的元素入栈道que_stack中
if (que_stack.empty() && !com_stack.empty())
{
while (!com_stack.empty())
{
que_stack.push(com_stack.top());
com_stack.pop();
}
}
com_stack.push(x);
}
int pop() {
if (que_stack.empty() && !com_stack.empty())
{
while (!com_stack.empty())
{
que_stack.push(com_stack.top());
com_stack.pop();
}
}
if (que_stack.empty() && com_stack.empty())
exit(0);
//正常情况
int top = que_stack.top();
que_stack.pop();
return top;
}
int peek() {
if (que_stack.empty() && !com_stack.empty())
{
while (!com_stack.empty())
{
que_stack.push(com_stack.top());
com_stack.pop();
}
}
if (que_stack.empty() && com_stack.empty())
exit(0);
return que_stack.top();
}
bool empty() {
return com_stack.empty() && que_stack.empty();
}
};