定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数( 时间复杂度应为O(1) )。
import java.util.Stack;
public class s {
Stack<Integer> stack = new Stack<>();
Stack<Integer> stackMin = new Stack<>();
public void push(int node) {
stack.push(node);
if (stackMin.isEmpty()) {
stackMin.push(node);
} else {
stackMin.push(stackMin.peek() > node ? node : stackMin.peek());
}
}
public void pop() {
stack.pop();
stackMin.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return stackMin.peek();
}
}
- 扩展:采用迭代器(了解即可)
public class o_20 {
Stack<Integer> stack = new Stack<>();
public void push(int node) {
stack.push(node);
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
int min = stack.peek();
int temp = 0;
Iterator<Integer> it = stack.iterator();
while (it.hasNext()) {
temp = it.next();
if (min > temp) {
min = temp;
}
}
return min;
}
关于栈的迭代,如果将1,2,3一次压入栈中,iterator迭代遍历后结果依然是1,2,3的顺序。
public static void iteratorTest(Stack stack) {
Iterator<Integer> test = stack.iterator();
while (test.hasNext()) {
System.out.println(test.next());
}
}
public static void main(String[] args) {
Stack<Object> ooo = new Stack<>();
ooo.push(2);
ooo.push(4);
ooo.push(6);
iteratorTest(ooo); //2,4,6
}