Design a max stack that supports push, pop, top, peekMax and popMax.
Input:
push(5)
push(1)
push(5)
top()
popMax()
top()
peekMax()
pop()
top()
Output:551515
class MaxStack
{
public:
stack<int> s;
stack<int> ms;
MaxStack()
{
// do intialization if necessary
}
/*
* @param number: An integer
* @return: nothing
*/
void push(int number)
{
s.push(number);
if(ms.empty()){
ms.push(number);
}
else if (!ms.empty() && number >= ms.top())
{
ms.push(number);
}
return;
}
/*
* @return: An integer
*/
int pop()
{
int n;
if (!s.empty())
{
n = s.top();
s.pop();
}
if (!ms.empty() && ms.top() == n)
{
ms.pop();
}
return n;
}
/*
* @return: An integer
*/
int top()
{
// write your code here
return s.top();
}
/*
* @return: An integer
*/
int peekMax()
{
// write your code here
return ms.top();
}
/*
* @return: An integer
*/
int popMax()
{
// write your code here
int n;
if (!ms.empty())
{
n = ms.top();
ms.pop();
}
while (!s.empty() && s.top() != n)
{
s.pop();
}
s.pop();
return n;
}
};