c - 通过从堆中删除值并将值插入堆中来同步文件和堆中的数据
问题描述
你在这个文件的第一行写了一个m数字,表示堆可以拥有的节点数,在接下来的m行,1 或 2 和旁边,一个指定的数字在树中使用。
您有 2 个操作(1 和 2):1 是添加一个元素,2 是删除最大的元素并显示它。
所以基本上,插入函数与堆函数绑定在末尾插入数字,然后将其放在前面。
此外,heapify 的删除功能是切换第一个和最后一个数字,然后删除最后一个数字(现在是第一个),但您还需要将其打印到另一个文件中。
在pla.txt文件中,您有如下内容:
12
1 18
1 12
1 3
2
1 3
1 15
2
2
1 8
2
1 19
2
12 代表节点的数量,如果我们读取1,它将执行插入,如果我们读取2,它将执行删除。我的问题是它不起作用,它只显示地址,而不是显示最大的数字。(数字2操作删除了堆中删除的最大数字,所以会在文件“cur.txt”中输入,18,15,12,8,19
)有什么问题?
#include <stdio.h>
void swap1(int c,int b)
{
int aux=c;
c=b;
b=aux;
}FILE *g=fopen("cur.txt","w");
void heapify(int a[],int index,int m)
{
int leftindex=2*index;
int rightindex=2*index+1;
int father=index;
if(leftindex<m&&leftindex>0 && a[leftindex]>a[father])
{
father=leftindex;
}
if(rightindex<m && rightindex>0&& a[rightindex]>a[father])
{
father=rightindex;
}
if(father!=index)
{
swap1(a[index],a[father] );
heapify(a,father,m-1);
}
}
void heap(int a[], int index)
{
int parent=(index-1)/2;
if(a[index]>a[parent] && a[parent]>0)
{
swap1(a[index],a[parent]);
heap(a,parent);
}
}
void insertion(int a[],int x,int m)
{
m++;
a[m-1]=x;
heap(a,m-1);
}
void deletetion(int a[],int m)
{
a[1]=a[m-1];
m=m-1;
heapify(a,1,m);
fprintf(g,"%d ",a[1]);
}
int main()
{
FILE *f=fopen("pla.txt","r");
int m;
fscanf(f,"%d",&m);
int op,x;
int a[m];
int z=1;
while(fscanf(f,"%d",&op)!=EOF)
{
if(op==1)
{
fscanf(f,"%d",&x);
insertion(a,x,z);
}
else
{
deletetion(a,z);
}
}
}
解决方案
更改fprintf(g,"%d ",&a[1]);
为删除功能fprintf(g,"%d ",a[1]);
。
还有一些潜在的错误。主要问题是您没有在函数中使用指针。因为 C 不支持引用参数。因此,您需要在交换函数中使用指针,并且还需要在参数m中使用指针来进行heapify、插入和删除函数。
推荐阅读
- android - CardView 在我的片段上不能完全滚动
- html - Bootstrap - 无法在导航栏中对齐 X 和 Y
- css - 如何仅在测验中的选定选项上显示背景颜色
- javascript - 通过 API 返回的数组重复映射子组件内的子组件
- javascript - 如何在反应中使用本地json文件打印数据
- angular - Angular FormArray - 无法读取 null 的属性“推送”
- java - 通用方法类型参数
- ios - 不存在捆绑 URL 确保您正在运行打包服务器
- flutter - 使fluttertext连续增长直到达到最大宽度,然后溢出
- python - 取一个 8 位数字并将它们分成两个 4 位数字