-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspecialstack.cpp
72 lines (59 loc) · 1.96 KB
/
specialstack.cpp
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
#include <iostream>
#include <stack>
class SpecialStack {
private:
std::stack<int> mainStack; // to store elements
std::stack<int> minStack; // to keep track of the minimum element
public:
// Function to push an element onto the stack
void push(int value) {
mainStack.push(value);
// Update minStack if the new element is smaller or equal
if (minStack.empty() || value <= minStack.top()) {
minStack.push(value);
}
}
// Function to pop the top element from the stack
void pop() {
if (!mainStack.empty()) {
// If the top element of mainStack is the minimum, pop from minStack as well
if (mainStack.top() == minStack.top()) {
minStack.pop();
}
mainStack.pop();
}
}
// Function to get the minimum element from the stack
int getMin() {
if (!minStack.empty()) {
return minStack.top();
} else {
// Handle the case where the stack is empty
std::cerr << "Stack is empty." << std::endl;
return -1; // or any other appropriate value
}
}
// Function to check if the stack is empty
bool isEmpty() {
return mainStack.empty();
}
// Function to check if the stack is full
bool isFull() {
// Since we are not using a fixed-size array, the stack is not limited in size
return false;
}
};
int main() {
SpecialStack specialStack;
specialStack.push(3);
specialStack.push(5);
std::cout << "Minimum element: " << specialStack.getMin() << std::endl;
specialStack.push(2);
specialStack.push(1);
std::cout << "Minimum element: " << specialStack.getMin() << std::endl;
specialStack.pop();
std::cout << "Minimum element after pop: " << specialStack.getMin() << std::endl;
specialStack.pop();
std::cout << "Minimum element after pop: " << specialStack.getMin() << std::endl;
return 0;
}