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());
}
}
实现min函数的栈
最新推荐文章于 2024-02-16 21:20:12 发布