[b]你的代码中主要有以下几个问题需要注意:
1. #include"Header.h " 这行代码包含了一个不必要的空格,它可能阻止编译器正确找到头文件。你应该使用 #include "Header.h" 。
2. 你在定义 struct Heap 之前就已经开始使用了这个类型,这可能会导致编译器报告未定义类型的错误。你需要先定义类型,然后再使用。
3. 在你的 Insert 函数中,当 heap->List[i/2]>num 为 false 时,会跳出循环,但此时 i 已经被除以2,这可能会导致数组越界错误。你需要在分配值给 heap->List[i
] 之前修复 i 。
4. 在 DeleteMin 函数中, heap->Size-1 会越过数组边界,如果 heap->Size 是0,那么结果是一个负数,这在C中是未定义的行为。
5. 你的代码中,heap的实例化在 Initialize 函数中发生,而你在main函数中传入的heap是 NULL ,这不是一个好的实践。你可以直接在 Initialize 函数中创建heap,无需在函数外部创建。
以下是修改后的代码:
Header.h
- #ifndef HEAP
- #define HEAP
- #define Cap 20
- struct Heap {
- int Capacity; //数组容量
- int Size; //当前数量
- int* List;
- };
- typedef struct Heap *H;
- H Initialize();
- int Isfull(H heap);
- int Isempty(H heap);
- void Insert(H heap, int num);
- void DeleteMin(H heap);
- void printf_all(H heap);
- #endif
复制代码
Heap.c
- #include <limits.h>
- #include <stdlib.h>
- #include<stdio.h>
- #include "Header.h"
- H Initialize() {
- H heap;
- heap =(H)malloc(sizeof(struct Heap));
- if(!heap) {
- perror("malloc error");
- exit(EXIT_FAILURE);
- }
- heap->List=(int*)malloc((Cap+1)*sizeof(int));
- if(!heap->List) {
- perror("malloc error") ;
- exit(EXIT_FAILURE);
- } else {
- heap->Capacity=Cap;
- heap->Size=0;
- heap->List[0]=INT_MIN;
- }
- return heap;
- }
- int Isempty (H heap) {
- return heap->Size == 0;
- }
- int Isfull(H heap) {
- return heap->Size == Cap;
- }
- void Insert (H heap, int num) {
- int i;
- if(!heap) {
- perror("heap is empty") ;
- exit(EXIT_FAILURE);
- }
- for(i=heap->Size+1;heap->List[i/2]>num;i/=2)
- heap->List[i]=heap->List[i/2];
- heap->List[i/2]=num;
- heap->Size++;
- }
- void DeleteMin(H heap) {
- int i,child;
- int Min,Max;
- if(!heap) {
- perror("heap is empty") ;
- exit(EXIT_FAILURE);
- }
- Min=heap->List[1];
- Max=heap->List[heap->Size];
- for(i=1;i*2<=heap->Size;i=child) {
- child=i*2;
- if(child != heap·>Size && heap->List[child] > heap->List[child+1])
- child++;
- if(Max > heap->List[child])
- heap->List[i]=heap->List[child];
- else
- break;
- }
- heap->List[i]=Max;
- heap->Size--;
- }
- void printf_all(H heap) {
- for(int i=1;i<=heap->Size;i++)
- printf("%d\n", heap->List[i]);
- }
复制代码
main.c
- #include <stdio.h>
- #include "Header.h"
- int main() {
- H heap = Initialize();
- int n=0;
- while(scanf("%d",&n)==1) {
- Insert(heap,n);
- }
- printf_all(heap);
- return 0;
- }
复制代码
注意,这些代码不会实现一个有效的堆数据结构,因为 Insert 和 DeleteMin 函数的实现不正确,它们不会保持堆的属性。你可能需要重新实现这两个函数以实现有效的堆数据结构。[/b]