我正在嘗試將單詞插入哈希表中,看起來它可以作業,但是當我嘗試在節點內列印單詞時(只是為了檢查它是否仍然正確),我得到了一個虛假值。當我的代碼提示輸入單詞時,我說'Hey',當它提示輸入位置時,我說'5'。列印出的字串(應該是節點內的單詞)是 HH9[]A\A]A^A_f。節點內的單詞發生了什么變化,我是否正確插入了節點?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct node
{
char word[20];
struct node *next;
}
node;
int main (void)
{
node* table[10];
char wrd[10];
printf("Word to insert: ");
fgets(wrd, 10, stdin);
int place;
printf("Place to insert word: ");
scanf("%d", &place);
node *n = malloc(sizeof(node));
if(n == NULL)
{
return 1;
}
strcpy(n->word, wrd);
if(table[place] == NULL)
{
n = table[place];
n->next = NULL;
}
else
{
n->next = table[place];
n = table[place];
}
printf("Word inside node: %s \n" , n->word);
}
uj5u.com熱心網友回復:
鏈表是鏈表,因為它沒有固定的大小。因此table陣列是多余的。你的鏈表作業需要的是記住錨點,僅此而已。
一個小例子:
Node *anchor = NULL;
Node *end = NULL;
Node *node = malloc(sizeof(Node));
node->next = NULL;
if (!end) //Initial state
anchor = end = node;
else //Every following node.
end = end->next = node;
此時,您仍然可以訪問node您剛剛填寫的內容。不要忘記稍后迭代您的串列和free那些分配。
uj5u.com熱心網友回復:
這段代碼沒有任何意義:
if(table[place] == NULL)
{
n = table[place]; // since we know table[place] is null, that sets n to null!
n->next = NULL; // We just set n to NULL, we can't access n->next!
}
else
{
n->next = table[place]; // This sets n to a garbage value since table[place] was never assigned a value
n = table[place]; // This leaks the value we malloc'ed. We were supposed to link it to the list!
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/355207.html
上一篇:如何繞過零大小的陣列?
下一篇:Nginx配置實體(動靜分離)
