1. 程式人生 > >設計一個帶有push,pop和max的棧

設計一個帶有push,pop和max的棧

#include "stdafx.h"
#include<iostream>
#include<stack>


using namespace std;


class stackWithMax
{
private:
stack<int> valueStack;
stack<int> maxStack;
public:
void push(int);
int pop();
int max();
};


void stackWithMax::push(int value)
{
if(maxStack.empty()||maxStack.top()<value)
{
maxStack.push(value);
}
valueStack.push(value);
}


int stackWithMax::pop()
{
int value=valueStack.top();
valueStack.pop();
if(value==maxStack.top())
{
maxStack.pop();
}
return value;
}


int stackWithMax::max()
{
return maxStack.top();
}
int _tmain(int argc, _TCHAR* argv[])
{
int number[]={5,1,2,7,3};
stackWithMax st;
for(int i=0;i<5;i++)
{
st.push(number[i]);
}
cout<<st.max();
cout<<endl;
for(int i=0;i<5;i++)
{
cout<<st.pop();
}
system("pause");
return 0;
}