#include <iostream>
#include <stack>
#include <climits>
class MinMaxStack {
private:
std::stack<int> mainStack;
std::stack<int> minStack;
std::stack<int> maxStack;
public:
void push(int element) {
mainStack.push(element);
if (minStack.empty() || element <= minStack.top()) {
minStack.push(element);
}
if (maxStack.empty() || element >= maxStack.top()) {
maxStack.push(element);
}
}
int pop() {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
int topElement = mainStack.top();
mainStack.pop();
if (topElement == minStack.top()) {
minStack.pop();
}
if (topElement == maxStack.top()) {
maxStack.pop();
}
return topElement;
}
int peek() {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
return mainStack.top();
}
bool isEmpty() {
return mainStack.empty();
}
int size() {
return mainStack.size();
}
int getMin() {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
return minStack.top();
}
int getMax() {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
return maxStack.top();
}
void clear() {
while (!isEmpty()) {
pop();
}
}
};
int main() {
MinMaxStack stack;
std::cout << "Pushing elements: 5, 3, 7, 1, 9" << std::endl;
stack.push(5);
stack.push(3);
stack.push(7);
stack.push(1);
stack.push(9);
std::cout << "Stack size: " << stack.size() << std::endl;
std::cout << "Top element: " << stack.peek() << std::endl;
std::cout << "Minimum element: " << stack.getMin() << std::endl;
std::cout << "Maximum element: " << stack.getMax() << std::endl;
std::cout << "\nPopping elements:" << std::endl;
while (!stack.isEmpty()) {
std::cout << "Popped: " << stack.pop() << std::endl;
if (!stack.isEmpty()) {
std::cout << "New min: " << stack.getMin() << std::endl;
std::cout << "New max: " << stack.getMax() << std::endl;
}
}
std::cout << "\nTesting clear operation" << std::endl;
stack.push(10);
stack.push(20);
std::cout << "Size before clear: " << stack.size() << std::endl;
stack.clear();
std::cout << "Size after clear: " << stack.size() << std::endl;
return 0;
}