一、栈与队列的关系
1. 232用栈实现队列
class MyQueue
{
public:
stack<int>stack_in;
stack<int>stack_out;
MyQueue()
{
}
void push(int x)
{
stack_in.push(x);
}
int pop()
{
if(stack_out.empty())//空的就是true
{
while(!stack_in.empty())
{
stack_out.push(stack_in.top());
stack_in.pop();
}
}
int result = stack_out.top();
stack_out.pop();
return result;
}
int peek()
{
if(stack_out.empty())//空的就是true
{
while(!stack_in.empty())
{
stack_out.push(stack_in.top());
stack_in.pop();
}
}
int result=stack_out.top();
return result;
}
bool empty()
{
if (stack_in.empty()&&stack_out.empty())
{
return true;
}
else
{
return false;
}
}
};
/**
* 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();
*/
2. 255用两个队列实现栈
class MyStack {
public:
queue<int> queue1;//这是用来模仿栈的
queue<int> queue2;
MyStack() {
}
void push(int x)
{
queue1.push(x);
}
int pop()
{
int size=queue1.size();
size--;
while(size--)
{
queue2.push(queue1.front());
queue1.pop();//从头部弹出元素
}
int result=queue1.back();
queue1.pop();
queue1=queue2;
while (!queue2.empty())
{
// 清空queue_out
queue2.pop();
}
return result