包含单词C的链接列表的哈希表

时间:2015-07-09 03:35:48

标签: c linked-list hashtable

我对C完全是新手,所以我遇到了哈希表和链表问题。 以下是我的代码:

typedef struct WordList {
   char *word;
   struct WordList *next;
} WordList;

typedef struct HashTable {
   int key;
   struct WordList value;
} HashTable;

#define TABLE_SIZE 10

HashTable *table[TABLE_SIZE] = { NULL };

//Insert element
void insertElement(int key, char *word) {
   int i = 0;

   // check if key has already existed
   while((table[i]->key != 0) && (i < TABLE_SIZE)) {
      if(table[i]->key == key) { // if find key    
         struct WordList wl = table[i]->value;
         // assign word to temp list then append to existed list
         struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));
         temp->word = word;
         temp->next = wl;
         wl = temp;
         table[i]->value = wl; // add  word to existed linked list

         return; // exit function and skip the rest
      }

      i++; // increment loop index 
   }

   // find a NULL slot and store key and value
   if(table[i]->key == NULL) {
      table[i]->key = key;

      struct WordList wl = table[i]->value;
      // assign word to temp list then append to existed list
      struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));
      temp->word = word;
      temp->next = wl;
      wl = temp;
      table[i]->value == wl;
   }
}

int main() {
   // test call
   insertElement(1, "blah\0"); 

   int i;

   for ( i=0; i < 10; i++)
   {
      printf("%d: ", i);

      struct HashTable *tableTemp = table[i];

      while (entryTemp != NULL)
      {
         printf("(%d)\n", tableTemp->key);
         tableTemp = tableTemp->next;
      }

      printf("\n");
   }

   return 0;
}

我收到此错误:

In function ‘insertElement’:
error: invalid initializer
struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));
                                                                   ^

你能告诉我哪个部分搞砸了吗? 我知道这里的编码风格也很糟糕,但你能先解决实际问题,然后再评论其余的问题吗?

1 个答案:

答案 0 :(得分:4)

struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));

请注意,左侧是结构,但右侧是结构 是一个指针。你可能想要:

struct WordList *temp = (struct WordList *)malloc(sizeof(struct WordList));