建立一個增加返回最小值的功能的棧
阿新 • • 發佈:2020-12-20
建立一個棧,增加返回最小值的功能
需求:
改造一個棧,在滿足基本的條件下,再新增一個返回最小值的方法
思路:
建立兩個棧,一個棧作為普通的資料(StackData)棧,另一個用來記錄最小值(StackMin),當新增資料的時候,data棧直接增加資料,而StackMin棧則取出當前最小值與新增值相比較,如果新增值較小,則StackMin棧新增新值,否則再新增最小值.
圖示:
程式碼:
public class SpecialStack { public static class StackArray{ private Stack<Integer> stackData; private Stack<Integer> stackMin; public StackArray() { this.stackData = new Stack<Integer>(); this.stackMin = new Stack<Integer>(); } public void push(int newNum) { if (this.stackMin.isEmpty()){ this.stackMin.push(newNum); }else{ this.stackMin.push(newNum < this.stackMin.peek()?newNum:this.stackMin.peek()); } this.stackData.push(newNum); } public int pop() { this.stackMin.pop(); return this.stackData.pop(); } public int getMin(){ if (this.stackMin.isEmpty()){ throw new RuntimeException("Your Stack is Empty !"); } return this.stackMin.peek(); } } public static void main(String[] args) { StackArray stack = new StackArray(); stack.push(3); System.out.println(stack.getMin()); stack.push(5); System.out.println(stack.getMin()); stack.push(2); System.out.println(stack.getMin()); stack.push(4); System.out.println(stack.getMin()); stack.push(1); System.out.println(stack.getMin()); } }