Menu
Coddy logo textTech

Practice #4

Lektion 12 von 13 im Kurs Stack - Datenstrukturen-Serie #1 von Coddy.

Lass uns einen Minimum/Maximum-Stack erstellen!

challenge icon

Aufgabe

Einfach

Füge deiner Stack-Klasse von vorhin zwei Funktionen hinzu:

  • min - gibt die aktuell kleinste Zahl im Stack zurück.
  • max - gibt die aktuell größte Zahl im Stack zurück.

Bonus: Versuche, bei jedem push oder pop nicht über alle Elemente im Stack zu iterieren.

Probier es selbst

#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;
}

Alle Lektionen in Stack - Datenstrukturen-Serie #1