/**
设计一个栈结构,使得取出栈中最大值时间复杂度为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();
}设计一个栈实现最大值函数
最新推荐文章于 2022-02-01 21:33:14 发布
设计一个栈结构,通过维护一个额外的栈来存储每次入栈元素的最大值索引,保证在O(1)的时间复杂度内获取栈中的最大值。在push和pop操作时同步更新最大值栈,实现快速获取最大值的功能。
1054

被折叠的 条评论
为什么被折叠?



