题目:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
Java 代码:
import java.util.Stack;
public class Solution {
int usedSize = 0;
int size = 10;
int[] elem = new int[size];
public void push(int node) {
if(usedSize == size){
System.out.println("栈已满~");
}else{
this.elem[usedSize++] = node;
}
}
public void pop() {
if(this.usedSize == 0){
System.out.println("栈已空~");
}else{
this.elem[usedSize--] = 0;
}
}
public int top() {
return this.elem[usedSize];
}
public int min() {
int min = this.elem[0];
for(int i = 0;i < usedSize;i++){
if(this.elem[i] < min){
min = this.elem[i];
}
}
return min;
}
}