/**
设计一个栈结构,使得取出栈中最大值时间复杂度为O(1)
就是开辟多一个存储最大值索引的栈,该栈和存储数据的栈保持同步,即栈顶指针同时作用这两个栈。
*/
#include <iostream>
using namespace std;
class myStack {
public:
myStack() {
MAX = 10;//栈的容量
top = -1;//oriSTack和maxStack的上标
maxIndex = -1;//最大值索引
oriStack = new int[MAX];//原始的stack
maxStack = new int[MAX]; //存放最大值索引的stack
}
void push(int elem) {
top++;
if(top>=MAX) { //如果上标大于MAX时
cout<<"Input error!";
return ;
}
oriStack[top] = elem;
if(elem>getMax()) {
maxStack[top] =top;//存放标记
maxIndex = top;
} else {
maxStack[top]=maxIndex;
}
}
int pop() {
if(top<0) {
cout<<"Output error!";
return -1;
}
int elem = oriStack[top];
if(top==0) {
maxIndex = -1;
} else if(top==maxIndex) {
maxIndex=maxStack[top-1];
}
top--;
return elem;
}
int getMax() {
if(maxIndex>=0) {
return oriStack[maxIndex];
} else {
return 0;
}
}
private:
int top;//栈a的最大值上标
int maxIndex;//最大值索引
int MAX;
int *oriStack;
int *maxStack;
};
int main() {
myStack ms;
ms.push(5);
ms.push(7);
ms.push(1);
ms.push(9);
ms.push(7);
ms.push(1);
ms.pop();
cout<<ms.getMax();
}