我有一个节点的哈希表。如何在哈希表中打印每个节点的每个值?

时间:2018-12-05 14:44:34

标签: c hashtable

我遇到了细分错误。这真的很基础,但我不知道怎么做。

据我了解,这就是我正在做的事情:

  • 我制作了一个名为node的结构。一个节点具有两个值:字符串WORD和指针NEXT。

  • 我制作了一个表,该表是两个节点的数组。

  • node1的值WORD等于“目标”。 node2的值WORD等于“ Jonas”。

  • 我试图打印两个节点的值WORD。

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    int main(void)
    {
        typedef struct node
        {
            char word[50];
            struct node *next;
        } node;
    
        node *table[2];
    
        strcpy(table[0]->word, "Goal");
        strcpy(table[1]->word, "Jonas");
    
        printf("%s\n", table[0]->word);
        printf("%s\n", table[1]->word);
    
    }
    

在我看来,这就是我想要做的:

表格:

________________
|        |      |
| "Goal" | NULL | -> this is node1
|________|______|
|        |      |
|"Jonas" | NULL | -> this is node2
|________|______|

1 个答案:

答案 0 :(得分:0)

以下是我做对的两种方法:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>


int main(void)
{
    typedef struct node
    {
        char word[50];
        struct node *next;
    } node;

    node table[2];

    strcpy(table[0].word, "Goal");
    strcpy(table[1].word, "Jonas");

    printf("%s\n", table[0].word);
    printf("%s\n", table[1].word);
}

或使用malloc():

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>


int main(void)
{
    typedef struct node
    {
        char word[50];
        struct node *next;
    } node;

    node *table[2];

    table[0] = malloc(sizeof *table[0]);
    table[1] = malloc(sizeof *table[0]);

    table[0]->next = NULL;
    table[1]->next = NULL;


    strcpy(table[0]->word, "Goal");
    strcpy(table[1]->word, "Jonas");

    printf("%s\n", table[0]->word);
    printf("%s\n", table[1]->word);

    free(table[0]);
    free(table[1]);
}