包含min函数的栈
2016-04-08 00:21
323 查看
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
import java.util.Stack; public class Solution { private Stack<Integer> stackData; private Stack<Integer> stackMin; public Solution(){ stackData = new Stack<Integer>(); stackMin = new Stack<Integer>(); } public void push(int node) { if(stackMin.isEmpty()){ stackMin.push(node); }else{ if(node <= this.min()){ stackMin.push(node); } } stackData.push(node); } public void pop() { if(stackData.isEmpty()){ // throws new RuntimeException("Your stack is empty"); } int value = this.stackData.pop(); if(value == this.min()){ stackMin.pop(); } } public int top() { if(stackMin.isEmpty()){ throw new RuntimeException("Your stack is empty."); } return stackMin.peek(); } public int min() { if(stackMin.isEmpty()){ throw new RuntimeException("Your stack is empty."); } return stackMin.peek(); } }
相关文章推荐
- 我的设计模式3
- 极简主义
- Hash算法初见
- 好久没写过博客,写一道今天的笔试题
- 2016第七届蓝桥杯C/C++ B组省赛题解 A题
- NameValuePair的用法
- 举例说明为什么不能设置简单密码
- 获取文件大小
- 2015CCPC湖南J题
- hihocoder #1285 智力竞赛
- Poj 2528-Mayor's posters 线段切割
- 学习 git基础命令
- LVS+Keepalived
- 栈的数组实现
- Java开发者值得关注的7款新工具
- C#获取Session、设置Session类文件
- Android大图片裁剪终极解决方案 原理分析
- 模取幂运算 计算a^b mod n
- 写固定文件大小的日志文件
- Android,IntentService