版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_29673403/article/details/82151243
最近跟人家讨论到这么一个问题,怎么求stack的最大值?
我的实现方法是再建一个辅助栈,用来存放stack的当前max值以及历史max值。
代码实现方式如下:
public multiStack<T>{
private Stack dataStack;
private Stack maxStack;
public multiStack(){
this.dataStack = new Stack();
this.maxStack = new Stack();
}
public void push(T value){
this.dataStack.push(value);
if(this.dataStack.empty()){
this.maxStack.push(value);
}else{
T maxValue = this.maxStack.peek();
if(value >= maxValue){
this.maxStack.push(value);
}
}
}
public T pop(){
T popValue = this.dataStack.pop();
T maxValue = this.maxStack.peek();
if(popValue == maxValue){
this.maxStack.pop();
}
return popValue;
}
public T getMax(){
return this.maxStack.peek();
}
}
这样就可以实现求取堆栈最大值的方法。由此引发思考,如果我要求取最大值的不是堆栈,是FIFO结构的队列,那么我应该如何实现呢?其实也不难,多用两个堆栈就好了,一个栈做输入,一个栈做输出,就可以很轻易的解决。
代码如下:
public MultiQueue<T>{
private Stack inputStack;
private Stack inputMaxStack;
private Stack outputStack;
private Stack outputMaxStack;
public MultiQueue(){
this.inputStack = new Stack();
this.inputMaxStack = new Stack();
this.outputStack = new Stack();
this.outputMaxStack = new Stack();
}
public void offer(T value){
this.inputStack.push(value);
if(this.inputMaxStack.isEmpty()){
this.inputMaxStack.push(value);
}else{
T maxValue = this.inputMaxStack.peak();
if(value >= maxValue){
this.inputMaxStack.push(value);
}
}
}
public T poll(){
if(this.outputStack.isEmpty()){
while(!this.inputStack.empty()){
T value = this.inputStack.pop();
T maxValue = this.inputMaxStack.peak();
if(value == maxValue){
this.inputMaxStack.pop();
}
this.outputStack.push(value);
if(this.outputMaxStack.isEmpty()){
this.outputMaxStack.push(value);
}else{
maxValue = this.outputMaxStack.peak();
if(value >= maxValue){
this.outputMaxStack.push(value);
}
}
}
}
T popValue = this.outputStack.pop();
T maxValue = this.outputMaxStack.peek();
if(popValue == maxValue){
this.outputStack.pop();
}
return popValue;
}
public T getMax(){
T inputMaxValue = this.inputMaxStack.peak();
T outputMaxValue = this.outputMaxStack.peak();
if(inputMaxValue >= outputMaxValue)
return inputMaxValue;
else
return outputMaxValue;
}
}
到此,就实现了两种数据结构如何求取最大值的问题。代码纯手敲的,要是有问题的话,不大意的告诉我把~共勉啊