Menu
CoddyTech

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 <stdio.h>
#include <string.h>
#include "stack.h"

int main() {
    Stack stack;
    Stack_init(&stack);
    char cmd[16];
    while (scanf("%15s", cmd) == 1) {
        if (strcmp(cmd, "push") == 0) {
            int x;
            scanf("%d", &x);
            Stack_push(&stack, x);
        }
        else if (strcmp(cmd, "pop") == 0) {
            printf("%d\n", Stack_pop(&stack));
        }
        else if (strcmp(cmd, "top") == 0) {
            printf("%d\n", Stack_top(&stack));
        }
        else if (strcmp(cmd, "size") == 0) {
            printf("%d\n", Stack_size(&stack));
        }
        else if (strcmp(cmd, "min") == 0) {
            printf("%d\n", Stack_min(&stack));
        }
        else if (strcmp(cmd, "max") == 0) {
            printf("%d\n", Stack_max(&stack));
        }
    }
    return 0;
}

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

Esercitati da solo: Compilatore C online