用两个栈实现队列
题目形容
用两个栈来实现一个队列,实现队列的Push和Pop操作。 队列中的元素为int类型。
题目链接: 用两个栈实现队列
代码
import java.util.Stack;/** * 题目: * 题目形容 * * 题目链接 * */public class Jz05 { // 入队列栈 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.size() == 0 && stack1.size() == 0) { throw new RuntimeException("该队列为空"); } if (stack2.size() == 0) { while (stack1.size() > 0) { stack2.push(stack1.pop()); } } return stack2.pop(); }}
【每日寄语】 所有看起来的侥幸,都源自坚定不移的致力。