001设计一个有GetMin功能的栈

来源:互联网 发布:linux mint 18和ubuntu 编辑:程序博客网 时间:2024/06/05 16:02

题目要求:实现一个特殊的栈,在实现栈的基础上,在返回栈中最小的元素的操作

#include<iostream>
#include<stack>
using namespace std;
class Mystack
{
public:
Mystack(){ }
void push(int newnum){
if (stackMin.empty()){
this->stackMin.push(newnum);
}
else if (newnum <= this->getmin())
{ stackMin.push(newnum);}
this->stackData.push(newnum);
}
int pop(){
if (this->stackData.empty()){
cout << "栈已经空了" << endl;
}
int value = stackData.top();


if (value==stackMin.top()){
stackMin.pop();
}
this->stackData.pop();
return value;
}
public:
int getmin(){
if (stackMin.empty()){
cout << "栈已经为空了" << endl;
}
else{ 
return stackMin.top();}
}
public:
stack<int>stackData;
stack<int>stackMin;
};


void main(){
Mystack aa;
aa.push(10);
aa.push(40);
cout<<aa.getmin()<<endl;
stack<int> a;
for (int i = 6; i < 10; i++)
{
a.push(i);
}
cout << a.top() << endl;
cout << a.size();
system("pause");
}

来源:程序员面试代码指南 -左程云

0 0