Menu
Coddy logo textTech

Esercitazione #4

Lezione 12 di 13 del corso Pila - Serie sulle strutture dati #1 di Coddy.

Creiamo uno stack minimo/massimo!

challenge icon

Sfida

Facile

Aggiungi alla tua classe Stack di prima due funzioni:

  • min - restituisce il numero minimo attualmente presente nello stack.
  • max - restituisce il numero massimo attualmente presente nello stack.

Bonus: Cerca di non iterare su tutti gli elementi dello stack a ogni push o pop.

Provalo tu

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

Tutte le lezioni di Pila - Serie sulle strutture dati #1

Esercitati da solo: Compilatore C online