Menu
Coddy logo textTech

parent

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

challenge icon

Challenge

Easy

Add a method parent to the MinHeap class.

It gets an integer i (an index into the heap) and returns the index of its parent: (i - 1) / 2 using integer division.

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, "parent") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", MinHeap_parent(&h, atoi(arg))); }
    }
    return 0;
}

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