栈实现队列
一个作为入队栈(stack1),一个作为出队栈(stack2)
入队:
元素入stack1;
出队:
若stack2有元素:直接出栈stack2;
若stack2无元素:stack1元素转入stack2 ,再出栈stack2;
class Solution
{
public:
void push(int node) {
while(!stack2.empty())
{
int data = stack2.top();
stack2.pop();
stack1.push(data);
}
stack1.push(node);
}
int pop() {
int val = 0;
while(!stack1.empty())
{
int data = stack1.top();
stack1.pop();
stack2.push(data);
}
if(!stack2.empty())
{
val = stack2.top();
stack2.pop();
}
return val;
}
private:
stack<int> stack1;
stack<int> stack2;
};