时间复杂度为O(1),求栈最大最小值和pop,push操作
#ifndef _MSTACK
#define _MSTACK
#include <stdio.h>
template<class T>
struct MStack{
MStack<T>* prev;
T Data;
};
template<class T>
class CMStack{
public:
CMStack(){
top =NULL;
count =0;
MaxTop =NULL;
MinTop =NULL;
};
T pop();
void Push(T Value);
T GetMaxValue();
T GetMinValue();
int GetCount();
private:
MStack<T>* top;
MStack<T>* MaxTop;
MStack<T>* MinTop;
T Data;
int count;
void MaxPush(T);
void MinPush(T);
void MaxPop();
void MinPop();
};
template<class T>
T CMStack<T>::pop(){
if (count ==0) {
return NULL;
}
T data;
MStack<T>* temp =top;
top =top->prev;
data =temp->Data;
delete temp;
temp =NULL;
if(data ==GetMaxValue() && MaxTop !=NULL){
MaxPop();
}
if(data ==GetMinValue() && MinTop !=NULL){
MinPop();
}
return data;
}
template<class T>
void CMStack<T>::Push(T value){
if (top ==NULL) {
top =new MStack<T>;
top->prev =NULL;
top->Data =value;
count ++;
}else{
MStack<T>* temp =new MStack<T>;
temp->Data =value;
temp->prev =top;
count++;
top =temp;
temp =NULL;
}
if (MaxTop == NULL) {
MaxPush(value);
}else if(value >=GetMaxValue()){
MaxPush(value);
}
if (MinTop == NULL) {
MinPush(value);
}else if(value <= GetMinValue()){
MinPush(value);
}
};
template<class T>
void CMStack<T>::MaxPop(){
if(MaxTop == NULL) return;
MStack<T>* temp =MaxTop;
MaxTop =MaxTop->prev;
temp->prev =NULL;
delete temp;
temp =NULL;
};
template<class T>
void CMStack<T>::MinPop(){
if(MinTop == NULL) return;
MStack<T>* temp =MinTop;
MinTop =MinTop->prev;
temp->prev =NULL;
delete temp;
temp =NULL;
};
template<class T>
void CMStack<T>::MaxPush(T val){
if (MaxTop ==NULL) {
MaxTop =new MStack<T>;
MaxTop->prev =NULL;
MaxTop->Data =val;
return ;
}
MStack<T>* temp =new MStack<T>;
temp->Data =val;
temp->prev =MaxTop;
MaxTop =temp;
temp =NULL;
};
template<class T>
void CMStack<T>::MinPush(T val){
if (MinTop ==NULL) {
MinTop =new MStack<T>;
MinTop->prev =NULL;
MinTop->Data =val;
return ;
}
MStack<T>* temp =new MStack<T>;
temp->Data =val;
temp->prev =MinTop;
MinTop =temp;
temp =NULL;
};
template<class T>
T CMStack<T>::GetMaxValue(){
return MaxTop->Data;
}
template<class T>
T CMStack<T>::GetMinValue(){
return MinTop->Data;
};
template<class T>
int CMStack<T>::GetCount(){
return count;
};
#endif
调试:
C/C++ code
#include "MStack.h"
#include <iostream>
using namespace std;
int main()
{
CMStack<int> s;
// for(int i =0;i<10;++i)
// s.Push(i % 5);
s.Push(6);s.Push(4);s.Push(2);s.Push(3);s.Push(7);s.Push(1);s.Push(6);s.Push(7);s.Push(8);s.Push(10);
s.Push(5);s.Push(9);s.Push(12);s.Push(13);s.Push(22);s.Push(1);s.Push(16);s.Push(17);s.Push(18);s.Push(10);
for (int i =0;i<s.GetCount() ;i++){
if(i ==8) {
s.Push(20);
cout<<"Push:"<<20<<endl;
}
if(s.GetCount()>0){
cout<<"Max Value:"<<s.GetMaxValue()<<";Min value:"<<s.GetMinValue()<<endl;
}
cout<<"Pop:"<<s.pop()<<endl;
}
return 0;
}