0

我正在编写一个在 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; 
4

1 回答 1

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;
  }

如果您还需要从表中删除,请将代码更改为使用双链表。

于 2013-11-13T09:33:32.753 回答