Practice #4
Lesson 12 of 13 in Coddy's Stack - Data Structures Series #1 course.
Let's create a minimum/maximum Stack!
Challenge
EasyAdd to your Stack class from before two functions:
min- returns the minimum number in the stack currently.max- returns the maximum number in the stack currently.
Bonus: Try not to iterate over all the elements in the stack each push or pop.
Try it yourself
#include <iostream>
#include <sstream>
#include <string>
#include "stack.h"
int main() {
Stack stack;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream iss(line);
std::string cmd;
if (!(iss >> cmd)) continue;
if (cmd == "push") {
int x; iss >> x; stack.push(x);
} else if (cmd == "pop") {
std::cout << stack.pop() << std::endl;
} else if (cmd == "top") {
std::cout << stack.top() << std::endl;
} else if (cmd == "size") {
std::cout << stack.size() << std::endl;
} else if (cmd == "min") {
std::cout << stack.min() << std::endl;
} else if (cmd == "max") {
std::cout << stack.max() << std::endl;
}
}
return 0;
}