首页 > 解决方案 > 通过从堆中删除值并将值插入堆中来同步文件和堆中的数据

问题描述

你在这个文件的第一行写了一个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);
        }
    }

}

标签: cfiletreeheapinsertion

解决方案


更改fprintf(g,"%d ",&a[1]);删除功能fprintf(g,"%d ",a[1]);

还有一些潜在的错误。主要问题是您没有在函数中使用指针。因为 C 不支持引用参数。因此,您需要在交换函数中使用指针,并且还需要在参数m中使用指针来进行heapify插入删除函数。


推荐阅读