首页 > 解决方案 > Insert and delete node from hash table in C

问题描述

in the code I made I have problems in deleting a node from the list of a hash table. In fact it seems that the first node of a list is connected to the last node of the previous list. For example: the first node of the list in position 6 of the array is connected to the last node of the list in position 5 of the array. Can you show me where I'm wrong?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_TARGA 10
#define NUM_PIANI 7

typedef struct
{
    char targa[MAX_TARGA];
    int ora;
    int min;
}Auto;

typedef struct nodo
{
    Auto info;
    struct nodo *link;
}Nodo;



int hash_function(char targa[]){
    int key = 0;

    for (int i = 0; i < NUM_PIANI; ++i) {
        key = key + (int)targa[i];
    }
    key = key % NUM_PIANI;
    if (key > NUM_PIANI){
        printf("Il valore hash supera la dimensione dell'array\n");
        abort();
    }else
        return key;
}

void inserisci_auto(Nodo* parcheggio[], Auto a){
    int key = hash_function(a.targa);
    Nodo *prec = NULL, *curr = parcheggio[key], *newnode;

    while (curr && strcmp(curr->info.targa, a.targa) <= 0){
        prec = curr;
        curr = curr->link;
    }

    newnode = malloc(sizeof(Nodo));
    if (!newnode)
        return;
    newnode->info = a;
    newnode->link = NULL;

    if (!prec){ //se stiamo inserendo il primo nodo
        newnode->link = parcheggio[key];
        parcheggio[key] = newnode;
    } else{ //se si inserisce in mezzo o in coda
        prec->link = newnode;
        newnode->link = curr;
    }
}

void elimina_auto(Nodo* parcheggio[], char targa[]){
    Nodo *prec = NULL, *curr;

    for (int i = 0; i < NUM_PIANI; ++i) {
        curr = parcheggio[i];
        while (curr){
            if (strcmp(curr->info.targa, targa) == 0) {
                if (!prec)
                    parcheggio[i] = curr->link;
                else
                    prec->link = curr->link;

                free(curr);
            }

            prec = curr;
            curr = curr->link;
        }
    }
}

I solved the problem. In the node deletion function, the prec pointer was not initialized to NULL each time the for loop passed to the next list. Now the correct function is:

void elimina_auto(Nodo* parcheggio[], char targa[]){
    Nodo *prec, *curr;

    for (int i = 0; i < NUM_PIANI; ++i) {
        prec = NULL;
        curr = parcheggio[i];
        while (curr){
            if (strcmp(curr->info.targa, targa) == 0) {
                if (!prec)
                    parcheggio[i] = curr->link;
                else
                    prec->link = curr->link;

                free(curr);
            }

            prec = curr;
            curr = curr->link;
        }
    }
}

标签: clisthashhash-function

解决方案


推荐阅读