写一个关于c++中堆的代码
时间: 2023-02-22 12:40:05 浏览: 49
好的,这是一个简单的关于 C 语言中实现堆的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_HEAP_SIZE 100
typedef struct {
int data[MAX_HEAP_SIZE];
int size;
} Heap;
void init_heap(Heap *h) {
h->size = 0;
}
void push(Heap *h, int value) {
if (h->size == MAX_HEAP_SIZE) {
printf("Error: Heap is full\n");
return;
}
h->data[h->size] = value;
int current = h->size;
int parent = (current - 1) / 2;
while (current > 0 && h->data[current] > h->data[parent]) {
int temp = h->data[current];
h->data[current] = h->data[parent];
h->data[parent] = temp;
current = parent;
parent = (current - 1) / 2;
}
h->size++;
}
int pop(Heap *h) {
if (h->size == 0) {
printf("Error: Heap is empty\n");
return -1;
}
int value = h->data[0];
h->data[0] = h->data[h->size - 1];
h->size--;
int current = 0;
int left_child = 2 * current + 1;
int right_child = 2 * current + 2;
while (left_child < h->size) {
int max_child = left_child;
if (right_child < h->size && h->data[right_child] > h->data[left_child]) {
max_child = right_child;
}
if (h->data[current] < h->data[max_child]) {
int temp = h->data[current];
h->data[current] = h->data[max_child];
h->data[max_child] = temp;
current = max_child;
left_child = 2 * current + 1;
right_child = 2 * current + 2;
} else {
break;
}
}
return value;
}
int main() {
Heap h;
init_heap(&h);
push(&h, 3);
push(&h, 2);
push(&h, 1);
printf("%d\n", pop(&h));
printf("%d\n", pop(&h));
printf("%d\n", pop(&h));
return 0;
}
```
这是一个最大堆的代码实现,在代码中定义了 `push` 和 `pop` 两个操作,分别