哈夫曼树c语言代码实现不用结构体
时间: 2023-08-05 18:22:00 浏览: 104
C语言实现哈夫曼树
以下是一个简单的哈夫曼树的 C 语言实现,不使用结构体:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义哈夫曼树节点结构体
typedef struct huf_node {
int weight; // 权值
int parent; // 双亲节点下标
int lchild; // 左孩子节点下标
int rchild; // 右孩子节点下标
} huf_node;
// 选择权值最小的两个节点
void select_min(huf_node *ht, int n, int *s1, int *s2) {
int i;
*s1 = *s2 = -1;
for (i = 0; i < n; i++) {
if (ht[i].parent == -1) {
if (*s1 == -1 || ht[i].weight < ht[*s1].weight) {
*s2 = *s1;
*s1 = i;
} else if (*s2 == -1 || ht[i].weight < ht[*s2].weight) {
*s2 = i;
}
}
}
}
// 构建哈夫曼树
void create_huffman(huf_node *ht, int *w, int n) {
int i, s1, s2;
for (i = 0; i < n; i++) {
ht[i].weight = w[i];
ht[i].parent = -1;
ht[i].lchild = -1;
ht[i].rchild = -1;
}
for (i = n; i < 2 * n - 1; i++) {
select_min(ht, i, &s1, &s2);
ht[s1].parent = i;
ht[s2].parent = i;
ht[i].lchild = s1;
ht[i].rchild = s2;
ht[i].weight = ht[s1].weight + ht[s2].weight;
}
}
int main() {
int i, n;
int *w;
huf_node *ht;
printf("请输入权值个数:");
scanf("%d", &n);
w = (int *)malloc(n * sizeof(int));
ht = (huf_node *)malloc((2 * n - 1) * sizeof(huf_node));
printf("请输入%d个权值:", n);
for (i = 0; i < n; i++) {
scanf("%d", &w[i]);
}
create_huffman(ht, w, n);
printf("哈夫曼树:\n");
for (i = 0; i < 2 * n - 1; i++) {
printf("%d %d %d %d\n", ht[i].weight, ht[i].parent, ht[i].lchild, ht[i].rchild);
}
free(w);
free(ht);
return 0;
}
```
阅读全文