代码
#include <stdio.h>
#include <stdlib.h>
#define swap(a,b) {\
__typeof(a) __tmp=a;\
a=b, b=__tmp;\
}
typedef struct Heap {
int *data, size, len;
} Heap;
Heap *initHeap(int n) {
Heap *h = (Heap *)malloc(sizeof(Heap));
h->data = (int *)malloc(sizeof(int) * n);
h->size = n, h->len = 0;
return h;
}
void freeHeap(Heap *p) {
if (!p) return ;
free(p->data);
free(p);
return ;
}
int push(Heap *h, int val) {
if (!h || h->size == h->len) return 0;
h->data[h->len] = val;
int ind = h->len;
while (ind > 0 && h->data[ind] > h->data[(ind - 1) / 2]) {
swap(h->data[ind], h->data[(ind - 1) / 2]);
ind = (ind - 1) / 2;
}
++h->len;
return 1;
}
void downAdj(int *arr, int ind, int len) {
while (ind * 2 + 1 < len) {
int tmp = ind;
int l = ind * 2 + 1, r = ind * 2 + 2;
if (arr[l] > arr[tmp]) tmp = l;
if (r < len && arr[r] > arr[tmp]) tmp = r;
if (tmp == ind) break;
swap(arr[tmp], arr[ind]);
ind = tmp;
}
return ;
}
int isEmpty(Heap *h) {
return !h || !h->len;
}
int pop(Heap *h) {
int ret = h->data[0];
h->data[0] = h->data[h->len - 1];
--h->len;
downAdj(h->data, 0, h->len);
return ret;
}
int main() {
return 0;
}