题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路介绍:
用两个栈实现一个队列,其实就是压栈的时候,将所有数压入一个栈中,当Pop的时候,先判断第二个栈区是否为空,如果不为空,则直接将第二个栈中数Pop ,如果为空,就把第一个栈顶的数压入第二个栈中,直到第一个栈区内无数据,然后再Pop第二个栈区的数据即可。
解题代码:
stack<int> stack1;
stack<int> stack2;
void Solution::push(int node)
{
stack1.push(node);
}
int Solution::pop()
{
int t = 0;
int j = 0;
int length = stack1.size();
if (stack2.empty())
{
for (int i = 0;i < length;i++)
{
j = stack1.top();
stack2.push(j);
stack1.pop();
}
}
t = stack2.top();
stack2.pop();
return t;
}