插入
Coddy 堆与优先队列:数据结构系列 #7 课程的第 5 课,共 14 课。
挑战
简单为 MinHeap 类添加一个 insert 方法。
它接收一个整数 value:
- 将
value追加到heap的末尾。 - 向上筛选:当新元素小于其父节点时,交换它们。当新元素不再较小或到达根节点时停止。
亲手试试
#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, "dump") == 0) {
for (int idx = 0; idx < h.count; idx++) { if (idx > 0) printf(" "); printf("%d", h.heap[idx]); }
printf("\n");
}
}
return 0;
}
堆与优先队列:数据结构系列 #7中的所有课
自己练习: C 在线编译器