Menu
CoddyTech

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

Alle Lektionen in Stack – Datenstrukturen Serie #1

Übe selbstständig: Online-C-Compiler