剑指offer 21. 包含min函数的栈
2017-05-09 17:10
281 查看
// 题目:写一个模拟栈的类,而且要多一个输出当前最小值的函数min() // 解法:加入最小数栈,将每次输入的数与栈顶数进行比较并进行相应的操作 class myStack{ private static int index = -1; //index表示当前指针 private static int[] value = new int[999]; //保存元素 private static int[] minValue = new int[999]; //保存最小值 public void push(int input){ index++; value[index] = input; if(index == 0){ minValue[index] = input; }else{ if(minValue[index-1]>input){ //如果比当前值小则存入更新这个元素加入后的最小值 minValue[index] = input; }else{ minValue[index] = minValue[index-1]; } } } public int peek(){ if(index == -1){ System.out.println("null"); return -1; } return value[index]; } public int min(){ if(index == -1){ System.out.println("null"); return -1; } return minValue[index]; } public int pop(){ if(index == -1){ System.out.println("null"); return -1; } index--; return value[index+1]; } public boolean isEmpty(){ if(index == -1){ return true; }else{ return false; } } } public class Main { public static void main(String[] args) { myStack s = new myStack(); s.push(1); System.out.println(s.pop()); System.out.println(s.min()); System.out.println(s.isEmpty()); } }
相关文章推荐
- 剑指Offer-包含min函数的栈
- 剑指offer题21_包含min函数的栈
- (十四)剑指offer之栈的压入弹出序列及包含min函数的栈
- 剑指offer(22):包含min函数的栈
- 剑指offer:包含min函数的栈
- 剑指OFFER之包含min函数的栈(九度OJ1522)
- 剑指offer_面试题21_包含min函数的栈
- 剑指offer:包含min函数的栈
- 剑指Offer 21:包含min函数的栈
- 【剑指offer】13,包含min函数的栈
- 剑指offer-20.包含min函数的栈
- 剑指offer 面试题21 包含min函数的栈
- 【剑指offer】包含min函数的栈
- 【剑指Offer面试编程题】题目1522:包含min函数的栈--九度OJ
- 剑指offer 包含min函数的栈
- 【剑指Offer】面试题21:包含min函数的栈
- 剑指offer--面试题21:包含min函数的栈--Java实现
- 【剑指offer 面试题21】包含min函数的栈
- 剑指offer 21 包含min函数的栈
- 【剑指offer】包含min函数的栈