设计一个栈实现最大值函数
来源:互联网 发布: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
- 设计一个栈实现最大值函数
- 用JavaScript脚本语言设计并实现一个函数,将三位数重新排列输出最大值
- 一个求最大值与最小值的函数
- 一个求最大值与最小值的函数
- 如何构造一个平滑的最大值函数
- 设计一个指向函数的一个指针,处理一个一维数组,调用该函数三次可以输出总和,最大值,平均值
- java实现函数重载,求最大值!
- 实现可变参数函数:Max,求最大值。
- python自定义函数实现最大值的输出
- python自定义函数实现最大值的输出
- 遗传算法求解函数最大值Java实现
- 随笔:设计一个栈结构,使得取出栈中最大值时间复杂度为O(1)
- C++使用两个栈实现一个可以获取栈中最大值和最小值的栈
- 使用可变参数,实现函数,求函数参数的最大值
- 求一个数组中的最大值。定义成函数
- 写了一个求最大值与最小值的函数
- 求一个数组中最大值函数的下标值
- C 编写求一个数组中最大值的函数
- Linux使用jstat命令查看jvm的GC情况
- Redis is configured to save RDB snapshots
- 习题7-10:守卫棋盘(dfs迭代加深)
- 百度地图的使用
- Numpy学习笔记
- 设计一个栈实现最大值函数
- [codeforces246E]Blood Cousins Return(dsu on the tree+STL)
- Fresco图片加载框架
- 初识construct 2
- LauncherRootView和DragLayer的布局过程
- 前端工程化
- SpringMvc Controller介绍和常用注解
- java AWT菜单
- (UART 与 USART有什么区别)&(SPI、I2C、UART三种串行总线协议的区别)