题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
栈是先进后出,队列是先进先出,两个栈分别为stack1和stack2,入队时直接把节点推入stack1,出队时,根据栈和队列的特性,把stack1的元素一个个出栈,在一个个入栈到stack2中,此时satck2的出栈元素顺序正好是元素入队顺序。
代码
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() {
if (stack2.empty())
while(!stack1.empty())
stack2.push(stack1.pop());
return stack2.pop();
}