用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
入队列:将元素依次进入Stack1中.
出队列:如果Stack2是空的,将Stack1中的元素全部移到Stack2中,从Stack2中出队列。如果非空,直接从Stack2中出队列.
package Chapter2_jichuzhishi; import java.util.Stack; /** * @Name: * @Description:用两个栈来实现一个队列,完成队列的Push和Pop操作。 * 队列中的元素为int类型。 * @Author: Allen */ public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.add(node); } public int pop() { if(stack1.isEmpty()&&stack2.isEmpty()){ throw new RuntimeException("Queue is empty"); } if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.add(stack1.pop()); } } return stack2.pop(); } }