我正在尝试创建一个链接列表数组,该列表将名称存储在名称的哈希值提供的索引位置。
由于某种原因,所有以前的插入都将被最新的插入替换。
struct Node{
char *key;
struct Node *next;
};
struct Table{
struct Node **entrypoint;
};
void InsertData(struct Table* table, const char *const name){
//char dest[100];
//strncpy(dest, name, 50);
int hashIndex = HashVal(name);
printf("Index Value is %d\n", hashIndex);
struct Node *new_node;
new_node = (struct Node* )malloc(sizeof(struct Node));
new_node->key = (char *)malloc((strlen(name)+1)*sizeof(char));
if(table->entrypoint[hashIndex] == 0){
table->entrypoint[hashIndex] = new_node;
strcpy(new_node->key, name);
new_node->next = NULL;
}
else{
struct Node *cursor = table->entrypoint[hashIndex];
while(cursor->next != NULL)
cursor = cursor->next;
cursor->next = new_node;
strcpy(new_node->key, name);
new_node->next = NULL;
}
//DISPLAY LIST
//int count = 0;
struct Node *temp;
for(int i = 0; i < 15; i++){
if(table->entrypoint[i] == NULL)
printf("%d: \n", i);
else{
temp = table->entrypoint[i];
printf("%d: ", i);
printf("%s ", temp->key);
//count = 0;
while(temp->next != NULL){
printf("%s ", temp->key);
temp = temp->next;
count++;
}
//printf("No. of times ran: %d", count);
printf("\n");
}
}
}
创建的节点数及其在链表中的位置正常。
但是所有插入都将被最终插入替换
预期结果:
InsertData(&table, "Jeffrey Lars");
InsertData(&table, "Neal Rhine");
InsertData(&table, "Ledley King");
Table:
0:
1:
2:
3: Jeffrey Lars, Ledley King
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14: Neal Rhine
实际结果:
InsertData(&table, "Jeffrey Lars");
InsertData(&table, "Neal Rhine");
InsertData(&table, "Ledley King");
Table:
0:
1:
2:
3: Ledley King, Ledley King
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14: Ledley King
有人可以指出我做错了什么。谢谢