-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathstackWithMaxElement.cpp
More file actions
70 lines (56 loc) · 1.27 KB
/
stackWithMaxElement.cpp
File metadata and controls
70 lines (56 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <stack>
#include <stdexcept>
class StackWithMaxElement
{
private:
std::stack<int> mainStack;
std::stack<int> maxStack;
public:
void push(int i)
{
mainStack.push(i);
if(maxStack.empty() || i >= maxStack.top())
{
maxStack.push(i);
}
}
void pop()
{
if(mainStack.empty())
{
throw std::runtime_error("Stack is empty");
}
if(mainStack.top() == maxStack.top())
maxStack.pop();
mainStack.pop();
}
int top()
{
if(mainStack.empty())
{
throw std::runtime_error("Stack is empty");
}
return mainStack.top();
}
int max()
{
if(maxStack.empty())
{
throw std::runtime_error("Stack is empty");
}
return maxStack.top();
}
bool empty()
{
return mainStack.empty();
}
};
int main()
{
StackWithMaxElement stack;
stack.push(1);
stack.push(5);
stack.push(4);
std::cout<<stack.max();
}