This implementation seems to work. I would love to get any suggestions / comments on how this code could be improved. Are there any potential memory management issues? Any additional methods that would be useful (also, from educational point of view) to implement? Thank you!
Stack.hpp
#ifndef STACK_H
#define STACK_H
#include <iostream>
#include <memory>
#include <vector>
#include <stdexcept>
class Stack {
private:
struct Node {
int val;
// To get min and max value of stack in O(1):
int maxVal = std::numeric_limits<int>::min();
int minVal = std::numeric_limits<int>::max();
};
std::vector<Node> currStack;
public:
int size() const { return currStack.size(); }
bool empty() const { return currStack.empty(); }
void pop() { currStack.pop_back(); }
void push(int val);
int top() const; // O(1)
int min() const; // O(1)
int max() const; // O(1)
};
#endif /* STACK_H */
Stack.cpp
#include "Stack.hpp"
void Stack::push(int val) {
Node tempNode;
tempNode.val = val;
if (this->empty()) {
tempNode.minVal = val;
tempNode.maxVal = val;
} else {
tempNode.minVal = std::min(currStack.back().minVal, val);
tempNode.maxVal = std::max(currStack.back().maxVal, val);
}
currStack.push_back(tempNode);
}
int Stack::top() const {
if (currStack.empty()) {
throw std::out_of_range ("Stack is empty");
}
return currStack.back().val;
}
int Stack::min() const {
if (currStack.empty()) {
throw std::out_of_range ("Stack is empty");
}
return currStack.back().minVal;
}
int Stack::max() const {
if (currStack.empty()) {
throw std::out_of_range ("Stack is empty");
}
return currStack.back().maxVal;
}
main.cpp
#include "Stack.hpp"
int main() {
// Stack init
Stack myStack;
std::cout << "Empty? " << myStack.empty() << "\n";
std::cout << "Size: " << myStack.size() << "\n";
try {
std::cout << "Top: " << myStack.top() << "\n";
std::cout << "Min: " << myStack.min() << "\n";
std::cout << "Max: " << myStack.max() << "\n";
}
catch (const std::out_of_range& e) {
std::cout << "Out of range error. " << e.what() << "\n";
}
std::cout << "Push some integers: \n";
myStack.push(5);
myStack.push(3);
myStack.push(7);
std::cout << "Empty? " << myStack.empty() << "\n";
std::cout << "Size: " << myStack.size() << "\n";
try {
std::cout << "Top: " << myStack.top() << "\n";
std::cout << "Min: " << myStack.min() << "\n";
std::cout << "Max: " << myStack.max() << "\n";
}
catch (const std::out_of_range& e) {
std::cout << "Out of range error. " << e.what() << "\n";
}
std::cout << "Pop some integers: \n";
myStack.pop();
std::cout << "Empty? " << myStack.empty() << "\n";
std::cout << "Size: " << myStack.size() << "\n";
try {
std::cout << "Top: " << myStack.top() << "\n";
std::cout << "Min: " << myStack.min() << "\n";
std::cout << "Max: " << myStack.max() << "\n";
}
catch (const std::out_of_range& e) {
std::cout << "Out of range error. " << e.what() << "\n";
}
}