-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxStack.cpp
More file actions
75 lines (60 loc) · 1.24 KB
/
MaxStack.cpp
File metadata and controls
75 lines (60 loc) · 1.24 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
71
72
73
74
75
//
// Created by Mayank Parasar on 2019-12-19.
//
/*
* Implement a class for a stack that supports all the regular functions (push, pop) and
* an additional function of max() which returns the maximum element in the stack
* (return None if the stack is empty). Each method should run in constant time.
*
s = MaxStack()
s.push(1)
s.push(2)
s.push(3)
s.push(2)
print s.max()
# 3
s.pop()
s.pop()
print s.max()
# 2
*/
#include <iostream>
#include <vector>
using namespace std;
class MaxStack {
public:
MaxStack() {
// default
}
void push(int val) {
m_stack.push_back(val);
return;
}
int pop() {
if(m_stack.size() == 0) {
cout << "MaxStack::pop() called on a empty vector" << endl;
return (-1);
}
int tmp = m_stack.back();
m_stack.pop_back();
return tmp;
}
int max() {
return (*max_element(m_stack.begin(), m_stack.end()));
}
private:
vector<int> m_stack;
};
int main() {
MaxStack *s = new MaxStack();
s->push(1);
s->push(2);
s->push(3);
s->push(2);
cout << s->max() << endl;
s->pop();
s->pop();
cout << s->max();
delete s;
return 0;
}