实例化 | Stack<Object> stack=new Stack<>(); |
判断是否为空 | stack.isEmpty() |
取栈顶值(不出栈) | stack.peek() |
进栈 | stack.push(Object); |
出栈 | stack.pop(); |
问题描述:
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
version 1.0代码:存在瑕疵,就是数组大小太大太小都会存在问题
/**
* 数组
*/
private int[] items;
/**
* 栈大小
*/
private int count;
public MinStack() {
this.items = new int[999];
this.count = 0;
}
/**
* 将元素 x 推入栈中
* @param x
*/
public void push(int x) {
items[count] = x;
++count;
System.out.println("push栈大小:"+count);
}
/**
* 删除栈顶的元素
*/
public void pop() {
if (count >= 0) {
--count;
}
System.out.println("pop栈大小:"+count);
}
/**
* 获取栈顶元素
* @return
*/
public int top() {
int top = items[ count - 1];
System.out.println("top栈大小:"+count);
return top;
}
/**
* 检索栈中的最小元素
* @return
*/
public int getMin() {
if (this.count < 1) {
return -1;
}
int min = items[0];
for (int i = 0; i < count; i++) {
if (items[i] < min) {
min = items[i];
}
}
return min;
}
}
version2.0代码:使用Stack操作
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> min_stack;
public MinStack() {
stack = new Stack<>();
min_stack = new Stack<>();
}
public void push(int x) {
stack.push(x);
if(min_stack.isEmpty() || x <= min_stack.peek()){
min_stack.push(x);
}
}
public void pop() {
if(stack.pop().equals(min_stack.peek())) {
min_stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min_stack.peek();
}
}