父节点
Coddy 堆与优先队列:数据结构系列 #7 课程的第 4 课,共 14 课。
挑战
简单在 MinHeap 类中添加一个 parent 方法。
它接收一个整数 i(堆中的一个索引),并使用整数除法返回其父节点的索引:(i - 1) / 2。
亲手试试
#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;
}
堆与优先队列:数据结构系列 #7中的所有课
自己练习: C 在线编译器