程序填空题:Hash Insertion
The function is to insert an item into the hash table `ht[]` with the hash function `hash`. Here a `list` node contains `item` which is of `element` type, and a `next` pointer. If the insertion is successful, the function must return 1, or 0 if not.
```c++
int insert( struct element item, list_pointer ht[] )
{
int ret, hash_value;
list_pointer ptr, trail, lead;
ret = 1;
hash_value = hash(item.key);
trail = NULL; lead = ht[hash_value];
for ( ; lead; trail = lead, lead = lead->next) {
if (!strcmp(lead->item.key, item.key)) {
printf("The key is in the table\n");
ret = 0;
}
}
if (ret) {
ptr = (list_pointer)malloc(sizeof(struct list));
@@[ptr->item = item](3);
ptr->next = NULL;
if (trail)
@@[trail->next = ptr](3);
else
@@[ht[hash_value] = ptr](3);
}
return ret;
}
```
答案:
第1空:ptr->item = item
第2空:trail->next = ptr
第3空:ht[hash_value] = ptr
```c++
int insert( struct element item, list_pointer ht[] )
{
int ret, hash_value;
list_pointer ptr, trail, lead;
ret = 1;
hash_value = hash(item.key);
trail = NULL; lead = ht[hash_value];
for ( ; lead; trail = lead, lead = lead->next) {
if (!strcmp(lead->item.key, item.key)) {
printf("The key is in the table\n");
ret = 0;
}
}
if (ret) {
ptr = (list_pointer)malloc(sizeof(struct list));
@@[ptr->item = item](3);
ptr->next = NULL;
if (trail)
@@[trail->next = ptr](3);
else
@@[ht[hash_value] = ptr](3);
}
return ret;
}
```
答案:
第1空:ptr->item = item
第2空:trail->next = ptr
第3空:ht[hash_value] = ptr