Anagram Solver C.

时间:2015-07-06 13:09:44

标签: c linked-list hashtable anagram

我对C完全是新手,所以我遇到了哈希表和链表问题。我正在制作一个字谜解算器。我在网上找到很多例子,但是每个人都做得不同而且相当复杂,所以我现在真的很困惑。

我对该计划的大部分实施都很满意。但是我一开始就陷入困境。

所以我需要创建一个哈希表,在每个条目中,键是一个int,值是一个链接的单词列表。

我获取密钥或哈希值的方法是将单词转换为数字。例如,A是1,B是2,C是3,AB是3,BC是5,ABC是6,依此类推。我想这些单词应该不区分大小写,以使事情变得更容易。

以下是我正在处理的代码。我很确定没有正确的语法。现在我只是在研究桌子的结构。

typedef struct Entry {
   int key;
   char *word;
   Entry *next;
} Entry;

typedef struct HashTable {
   int size; 
   Entry *entry; 
} HashTable;

// initialize table
HashTable* create(int size) {
   HashTable *table = (HashTable *)malloc(sizeof(HashTable));
   table->entry = (Entry *)malloc(sizeof(Entry) * size);
   table->size = size;

   int i;
   for (i = 0; i < size; i++) {
      table->entry[i].key = 0; // All entries to be 0
   }

   return table;
}

// hash the word
int getHash(char *word)
{
   // How do I implement a loop here
}

void insert(HashTable *table, int key, char *word) {
   int hash = getHash(word);
   int i = 0;

   // if key has already existed, find and add to linked list
   while(table->entry[hash].key != 0 && (i < table->size)) {
      if(table->entry[hash].key == key) {
         table->entry[hash].word = word;
         return; /*  */
      }

      //hash = (hash + 1); // I'm also stuck with incrementing the hash value 
      i++; // increment loop index 
   }

   // if key does not exist, find a '0 slot', and store the key and value
   if(table->entry[hash].key == 0) {
      table->entry[hash].key = key;
      table->entry[hash].word = word;
   }
}

1 个答案:

答案 0 :(得分:0)

我建议从一个相当简单的方法开始,从anagrams找到word的{​​{1}}。

text