繁体   English   中英

在C中单独链接

[英]separate chaining in C

我正在编写一个代码,该代码在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; 

对不起,不明白你的代码是对的,这是我的版本:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM