设计包含min 函数的栈,java版本

2.设计包含min 函数的栈。
定义栈的数据结构,要求添加一个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());

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值