题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
入队的时候就是把其入到stack1;
出队的时候首先把栈1弄到栈2,这时候栈2的顶部就是队首了,然后再获取栈2的顶部就是队首,并把栈顶出队(相当于对首出队)
这时候再把栈2弄回栈1
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while( !stack1.empty() )
{
int tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
int res = stack2.top();
stack2.pop();
while(!stack2.empty())
{
int tmp = stack2.top();
stack2.pop();
stack1.push(tmp);
}
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
JAVA版本:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while(!stack1.empty()) {
stack2.push(stack1.peek());//获取栈顶是peek函数
stack1.pop();
}
int res = stack2.peek();
stack2.pop();
while(!stack2.empty()) {
stack1.push(stack2.peek());
stack2.pop();
}
return res;
}
}