怀化网站制作南宁网站推广哪家好
用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的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();}
}
【每日寄语】 所有看起来的幸运,都源自坚持不懈的努力。