题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Collections;
import java.util.LinkedList;
import java.util.Stack;
public class Solution {
private Stack<Integer> stack = new Stack<>();;
private Integer minValue = Integer.MAX_VALUE;
private LinkedList<Integer> linkedList = new LinkedList<>();
public void push(int node) {
if (node < minValue) {
minValue = node;
}
stack.add(node);
linkedList.add(node);
Collections.sort(linkedList);
}
public void pop() {
if (!stack.isEmpty()) {
int topInteger = stack.pop();
if (topInteger==minValue) {
linkedList.removeFirst();
minValue = linkedList.getFirst();
} else {
for (int i=0; i<linkedList.size(); ++i) {
if (topInteger==linkedList.get(i)) {
linkedList.remove(i);
break;
}
}
}
}
}
public int top() {
if (!stack.isEmpty()) {
return stack.peek();
} else {
return (Integer)null;
}
}
public int min() {
return minValue;
}
}