c - 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;
}
}
}
解决方案
推荐阅读
- angular - 等待 openDialog 总是返回错误的 Angular 材质
- javascript - Node.js:express + promise-mysql 返回
- c# - HttpClient.SendAsync 从 api 接收响应的时间比预期的要长
- algorithm - 计算一个圆上的一组点可以组成的四边形的数量
- react-native - 从不同的屏幕更新状态值
- c# - 使用 Bresenham 的线算法从路径中检索所有 gps 坐标
- python-3.x - 在 Python 3 中将列表字符串化回列表
- c# - 当 x != 1 和 y != 0 时 x * y == y 可以吗?
- microservices - 通信微服务/微前端架构
- python - 如何有效地迭代 CSV 导入