Menu
Coddy logo textTech

extractMin

Lektion 7 von 14 im Kurs Heaps & Priority Queues - Datenstrukturen-Serie #7 von Coddy.

challenge icon

Aufgabe

Einfach

Fügen Sie der Klasse MinHeap eine Methode extractMin hinzu.

Sie nimmt keine Eingabe entgegen und:

  1. Wenn der Heap leer ist, gibt sie -1 zurück.
  2. Andernfalls entfernt sie die Wurzel, stellt den Heap mit siftDown wieder her und gibt den entfernten Wert zurück.

Probier es selbst

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "minheap.h"

int main() {
    MinHeap h;
    MinHeap_init(&h);
    char line[1024];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "insert") == 0) { char* arg = strtok(NULL, " \t"); if (arg) MinHeap_insert(&h, atoi(arg)); }
        if (strcmp(cmd, "peek") == 0) { printf("%d\n", MinHeap_peek(&h)); }
        if (strcmp(cmd, "extractMin") == 0) { printf("%d\n", MinHeap_extractMin(&h)); }
    }
    return 0;
}

Alle Lektionen in Heaps & Priority Queues - Datenstrukturen-Serie #7