整体思路总结如下:
1.stack1用来push数据,包括stack1为空,不为空的情况;
2.stack2用来pop数据。
当stack2为空时,将stack1除了栈底元素pop出来,按照出栈的顺序压入stack2中,直接pop stack1的元素就实现了出队操作;
当stack2不为空时,直接pop stack2。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.size() <= 0)//stack2为空
{
while (stack1.size()>0)//从stack1中弹出一个元素,入到stack2中
{
int data = stack1.top();
stack1.pop();
stack2.push(data);
}
}
if (stack2.size() == 0)
{
printf("the queue is empty!\n");
}
int head = stack2.top();
stack2.pop();
return head;
}
private:
stack<int> stack1;
stack<int> stack2;
};