Menu
Coddy logo textTech

peek

Lesson 6 of 14 in Coddy's Heaps & Priority Queues - Data Structures Series #7 course.

challenge icon

Challenge

Easy

Add a method peek to the MinHeap class.

It takes no input and returns:

  • The smallest value in the heap (the root at index 0) if the heap is not empty.
  • -1 if the heap is empty.

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)); }
    }
    return 0;
}

All lessons in Heaps & Priority Queues - Data Structures Series #7