Home > database >  Unable to delete an element from a list connected to hashtable
Unable to delete an element from a list connected to hashtable

Time:04-18

I have a hashtable that implement chaining collision. I have this function void elimina that should be used to eliminate an element from a list but the function doesn't eliminate the first element. For the other elements it works fine. How can I solve it?

void elimina() {
    int chiave, a;
    printf("\nQuale elemento vuoi elimiare?\n");
    scanf("%d", &chiave);
    a = chiave % DIM_TABELLA;
    c = head[a];
    struct nodo *newnodo = (struct nodo *)malloc(sizeof(struct nodo));
    newnodo->next = c;

    if (head[a] == NULL)
        printf("\nL'elemento non esiste");
    else {
        if (c->next->info == chiave) {
            c = c->next;
            free(c);
        } else
        if (c->next != NULL) {
            while (c->info != chiave) {
                b = c;
                c = c->next;
            }
        }
        if (c) {
            b->next = c->next;
            free(c);
        }
    }
}

CodePudding user response:

Multiple problems:

  • There is no need to allocate a new node in this function.
  • You do not link the next node before you free c
  • You never test if the first node matches the key.
  • You should use an unsigned number so the % operation always returns a positive number.

Here is a modified version:

void elimina(void) {
    printf("\nQuale elemento vuoi eliminare?\n");
    unsigned int chiave;
    if (scanf("%u", &chiave) != 1)
        return;
    unsigned int a = chiave % DIM_TABELLA;
    struct node *c = head[a];
    if (c == NULL) {
        printf("L'elemento non esiste\n");
        return;
    }
    if (c->info == chiave) {
        /* free the first node */
        head[a] = c->next;
        free(c);
    } else {
        while (c->next && c->next->info != chiave) {
            c = c->next;
        }
        if (c->next) {
            struct node *p = c->next;
            c->next = p->next;
            free(p);
        } else {
            printf("L'elemento non esiste\n");
        }
    }
}
  • Related