设计一个栈实现最大值函数

来源:互联网 发布:java volatile atomic 编辑:程序博客网 时间:2024/06/06 01:40
/**设计一个栈结构,使得取出栈中最大值时间复杂度为O(1)就是开辟多一个存储最大值索引的栈,该栈和存储数据的栈保持同步,即栈顶指针同时作用这两个栈。*/#include <iostream>using namespace std;class myStack {public:myStack() {MAX = 10;//栈的容量top = -1;//oriSTack和maxStack的上标maxIndex = -1;//最大值索引oriStack = new int[MAX];//原始的stackmaxStack = 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();}

阅读全文
0 0
原创粉丝点击