Ćwiczenie #4
Lekcja 12 z 13 w kursie Stos — struktury danych, część 1 w Coddy.
Stwórzmy stos minimum/maksimum!
Wyzwanie
ŁatwyDodaj do swojej wcześniejszej klasy Stack dwie funkcje:
min— zwraca aktualnie najmniejszą liczbę na stosie.max— zwraca aktualnie największą liczbę na stosie.
Bonus: Spróbuj nie iterować po wszystkich elementach stosu przy każdym wywołaniu push lub pop.
Spróbuj swoich sił
#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;
}
Wszystkie lekcje w sekcji Stos — struktury danych, część 1
Poćwicz samodzielnie: Kompilator C online