题目:定义栈的数据结构。要求添加一个min函数,能够得到栈的最小的元素。
要求min,pop,push的时间复杂度都是O(1)。
class Node{
private int data;
private int minData;
private Node next;
public Node(int data){
this.data = data;
this.next = null;
}
public int get Data(){
return data;}
public int getMinData(){
return minData;
}
public void setData(int data){
this.data = data;
}
public void setMinData(int data){
this.minData = data;
}
public void setNext(Node node){
this.next = node;
}
public Node getNext(){
return next;
}
}
package test;
public class MinStack {
private Node stack;
public MinStack() {
stack = null;
}
public boolean isEmpty() {
return stack == null;
}
public int min() {
if (isEmpty()) {
return Integer.MAX_VALUE;// 用最大的整数表示异常值;
}
return stack.getMinData();// 拿到最小的取值
}
/**
* 上面看一下
*
* @return
*/
public int pop() {
if (isEmpty()) {
return Integer.MAX_VALUE;
}
int temp = stack.getData();
stack = stack.getNext();
return temp;
}
public void push(int data) {
Node node = new Node(data);
if (!isEmpty()) {
if (node.getMinData() > stack.getMinData()) {// 拿到最小的数
node.setMinData(stack.getMinData());
}
node.setNext(stack);
}
stack = node;
}
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(5);
minStack.push(6);
minStack.push(7);
}
}