我正在编写一个代码,该代码在C中使用单独的链接,以便在发生冲突时在哈希表的同一索引上存储两个或多个值。但现在我没有得到如何在同一个哈希表索引上放置多个值。 我的代码删除了同一索引上最旧的值,只获取了新的值。 我在这里错过了什么?
void ht_set( hashtable_t *hashtable, char *key, char *value ) {
int bin = 0;
entry_t *newpair = NULL;//
entry_t *next = NULL;
entry_t *last = NULL;
bin = ht_hash( hashtable, key );//function to calculate hash index value
next = hashtable->table[ bin ];
while( next != NULL && next->key != NULL && strcmp( key, next->key ) > 0 ) {
last = next;
next = next->next;
}
/* There's already a pair. Let's replace that string. */
if( next != NULL && next->key != NULL && strcmp( key, next->key ) == 0 ) {
free( next->value );
next->value = strdup( value );
/* Nope, could't find it. Time to grow a pair. */
} else {
newpair = ht_newpair( key, value );
/* We're at the start of the linked list in this bin. */
if( next == hashtable->table[ bin ] ) {
newpair->next = next;
hashtable->table[ bin ] = newpair;
/* We're at the end of the linked list in this bin. */
} else if ( next == NULL ) {
last->next = newpair;
/* We're in the middle of the list. */
} else {
newpair->next = next;
last->next = newpair;
}
}
}
这是我的结构
struct entry_s {
char *key;
char *value;
struct entry_s *next;
};
typedef struct entry_s entry_t;
struct hashtable_s {
int size;
struct entry_s **table;
};
typedef struct hashtable_s hashtable_t;
答案 0 :(得分:2)
抱歉,不明白你的代码非常正确,这是我的版本:
struct node {
char* key,*value;
node* next;
} *hashtable[table_size];
void AddNode(char* key,char* value)
{
struct node* newnode=malloc(sizeof (struct node));
node->key=key;node->value=value;
node->next=hashtable[hash(key)];
hashtable[hash(key)]=node;
}
struct node* FindNode(char* key)
{
struct node* node=hashtable[hash(key)];
while(node!=NULL&&strcmp(key,node->key)!=0) node=node->next;
return node;
}
如果您还需要从表中删除,请更改代码以使用双链表。