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

不得已二 Java两个栈模拟一个队列

2019-11-14 10:30:37
字体:
来源:转载
供稿:网友

github:https://github.com/cbamls 欢迎加入 (java)全国各校IT精英 QQ群号: 467123855

很简单只要记住add操作不需要倒栈 poll 和peek的时候判断性的倒栈 肯定能设计出来

package com.offer.chapter1;import java.util.Stack;/** * CopyRright (c)2014-2016 Haerbin Hearglobal Co.,Ltd * PRoject: demo * Comments: * Author:cbam * Create Date:2017/2/4 * Modified By: * Modified Date: * Modified Reason: */public class Problem_02_TwoStacksQueue { private Stack<Integer> stackPush; private Stack<Integer> stackPop; public Problem_02_TwoStacksQueue() { stackPush = new Stack<>(); stackPop = new Stack<>(); } 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 this.stackPop.peek(); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表