如何在C中的单独链式哈希表中添加到链表

问题描述

这是我的问题的相关结构。

//A SymEntry is the building block for linked lists of (name,attribute) pairs
typedef struct SymEntry {
  char * name;
  void * attribute;
  struct SymEntry * next;
} SymEntry;

/*
Each symbol table is represented by a SymTab
size is the current number of lists in the separate chaining hash table
contents is an array of lists (i.e. points to the zeroth element in the array)
if current is not NULL it points to the current (name,attribute) pair in the symbol table
*/
  typedef struct {
    int size;
    SymEntry ** contents;
    SymEntry *current;
  } SymTab;

我有一个在c中创建符号表的项目。我们将实现一个单独的链接哈希表以完成此操作。我相信我正确创建了初始的空哈希表。下面是我的实现方式。

SymTab * createSymTab(int size) {
  int i;  
  SymTab *symbolTable = malloc(sizeof(SymTab));
  symbolTable->contents = (SymEntry**)malloc(size * sizeof(SymEntry));
  symbolTable->current = (SymEntry*)malloc(sizeof(SymEntry));
  symbolTable->size = size;

  for (i=0; i<size; i++) {
    SymEntry *newEntry = malloc(sizeof(SymEntry));
    newEntry -> name = NULL;
    newEntry -> attribute = NULL;
    newEntry -> next = NULL;
    
    symbolTable->contents[i] = newEntry;
    
  }
  symbolTable->current = NULL;
  return symbolTable;
}

我似乎也可以在链接列表中添加一个节点(SymEntry)的地方使用它。下面是我的代码,用于添加条目以及我的哈希方法

int enterName(SymTab * table,char *name) {
  if (findName(table,name) == 0) {
    int size = table->size;
    int hashNum = hash(name,&size);
    SymEntry *head = table->contents[hashNum];
    printf("Hash Number is %d\n",hashNum);
    if (head->name == NULL) {
      printf("Head is null\n");
      head->name = name;
      head->attribute = NULL;
    }
    else {
      printf("Head is not null\n");
      SymEntry *newNode = malloc(sizeof(SymEntry));
      newNode->name = name;
      newNode->attribute = NULL;
      newNode->next = head;
      head = newNode;
    }
    return 0;
  }
  return 1;
}

int hash(char *key,int * size) {
  int hash = 0;
  int i = 0;
  int sizeOfNum = *size;
  printf("Key Value: %s   Size of Number: %d\n",key,sizeOfNum);
  
  while (key && key[i]) {
    hash = (hash + key[i] % sizeOfNum);
    i++;
    }
  
  return hash % sizeOfNum;
}

最后,下面的代码是我用来测试的东西。如果我对所有内容的理解都是正确的,那么应该打印的名称是Jess,这是我的第二个条目,但我只看到Wes。这两个名称都散列为相同的数字,在这种情况下为5。当我将节点(SymEntry)添加到列表中时,我到底在做什么错?我的输出识别出我添加Jess时头部不是空的,所以我知道第一个条目是有效的。

int main(void) {
  SymTab * symbolTable = createSymTab(6);
  enterName(symbolTable,"wes");
  enterName(symbolTable,"jess");
  SymEntry * example = symbolTable->contents[5];
  printf("%s\n",example->name);
  return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)