package structure.stack_queue;import java.util.Stack;/** * 定義棧的資料結構,要求添加一個min函數,能夠得到棧的最小元素。要求函數min、push以及pop的時間複雜度都是O(1)。 * * @author Toy * */public class Stack_Min {Stack<Integer> s = new Stack<Integer>();Stack<Integer> mins = new Stack<Integer>();public void push(int d) {s.push(d);if (mins.isEmpty()) {mins.push(0);} else {int minIndex = mins.peek();if (d < s.get(minIndex)) {mins.push(s.size() - 1);} else {mins.push(minIndex);}}}public int pop() {if (s.isEmpty()) {System.out.println("empty stack");return -1;} else {mins.pop();return s.pop();}}public int min() {if (mins.isEmpty()) {System.out.println("empty stack");return -1;} else {int minIndex = mins.peek();return s.get(minIndex);}}/** * @param args */public static void main(String[] args) {int[] a = new int[] { 3, 4, 2, 5, 1, 6 };Stack_Min s = new Stack_Min();for (int i = 0; i < a.length; i++) {s.push(a[i]);}System.out.println(s.min());s.pop();s.pop();System.out.println(s.min());s.pop();s.pop();System.out.println(s.min());}}