2.设计包含min 函数的栈。
定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。
要求函数min、push 以及pop 的时间复杂度都是O(1)。
定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。
要求函数min、push 以及pop 的时间复杂度都是O(1)。
/**
*
*/
package com.lhp;
import java.util.EmptyStackException;
import java.util.Stack;
import java.util.Vector;
/**
2.设计包含min 函数的栈。
定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。
要求函数min、push 以及pop 的时间复杂度都是O(1)。
*/
class GStack<E extends Comparable<E>> extends Vector<E> {
/**
* v0.1
*/
private static final long serialVersionUID = -6719503943136573361L;
private Stack<Integer> minPosStack = new Stack<Integer>(); // 存储最小元素的位置
/**
* 栈的最小元素
* @return 最小元素
*/
public E min() {
return super.get(this.minPosStack.peek());
}
/**
* 入栈
* @param 元素
*/
public synchronized void push(E item) {
if (0 == super.size()) {
this.minPosStack.push(0);
} else {
if (item.compareTo(min()) <= 0) {
this.minPosStack.push(super.size());
} else {
this.minPosStack.push(this.minPosStack.peek()); // 维持不变
}
}
super.add(item);
}
/**
* 出栈
* @return 栈顶元素
*/
public synchronized E pop() {
E obj;
if (0 == super.size())
throw new EmptyStackException(); // return null
obj = super.get(super.size() - 1);
super.remove(super.size() - 1);
this.minPosStack.pop();
return obj;
}
public synchronized void print() {
if (0 == super.size()) {
System.out.print("HashCode: " + this.hashCode() + "; 空栈;");
return;
}
System.out.print("HashCode: " + this.hashCode() + "; 栈: ");
for (int i = 0; i < super.size(); i++) {
System.out.print(super.get(i) + " ");
}
System.out.println();
}
}
public class Tow {
public static void main(String[] args) {
GStack<Integer> s1 = new GStack<Integer>();
s1.push(new Integer(3));
s1.push(new Integer(6));
s1.push(new Integer(2));
s1.push(new Integer(1));
s1.push(new Integer(8));
s1.push(new Integer(7));
s1.pop();
s1.pop();
// s1.pop(); // 取消注释即得2
s1.print();
System.out.println("min(): " + s1.min());
}
}