首页 > 学院 > 开发设计 > 正文

栈和队列(二)

2019-11-08 01:56:00
字体:
来源:转载
供稿:网友

由两个栈实现队列

import java.util.Stack;public class sAD02 { public Stack<Integer> stackPush; public Stack<Integer> stackPop; public sAD02(){ stackPush = new Stack<Integer>(); stackPop = new Stack<Integer>(); } public void add(int pushInt){ stackPush.push(pushInt); } public int poll(){ if(stackPop.empty() && stackPush.empty()){ throw new RuntimeException("Queue is empty"); }else if(stackPop.empty()){ while (!stackPush.empty()){ stackPop.push(stackPush.pop()); } } return stackPop.pop(); } public int peek(){ if(stackPop.empty() && stackPush.empty()){ throw new RuntimeException("Queue is empty"); }else if(stackPop.empty()){ while(! stackPush.empty()){ stackPop.push(stackPush.pop()); } } return stackPop.peek(); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表