两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:栈颠倒两次就是队列的顺序,
栈1先入后出存储数据,需要pop时,只要用栈2再先入后出一遍栈1的数据,栈2读出来的数据就是先入先出
需要push时,把由栈2pop过的数据 以 先入后出的顺序写入栈1,然后栈1继续push数据就行
#include<stack> class Solution { public: void push(int node) { while(!stack2.empty()){ int val = stack2.top(); stack2.pop(); stack1.push(val); } stack1.push(node); } int pop() { while(!stack1.empty()){ int val = stack1.top(); stack1.pop(); stack2.push(val); } int node = stack2.top(); stack2.pop(); return node; } private: stack<int> stack1; stack<int> stack2; };