extractMin
Lesson 7 of 14 in Coddy's Heaps & Priority Queues - Data Structures Series #7 course.
Challenge
EasyAdd a method extractMin to the MinHeap class.
It takes no input and:
- If the heap is empty, returns
-1. - Otherwise, removes the root, restores the heap with siftDown, and returns the removed value.
Try it yourself
#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;
}