我需要一些有关单链表的帮助。我正在尝试为从我的文本文件中读取的每个单词插入一个新节点,并将其与字典文件中的单词进行比较。从那里,新节点被插入到哈希表中。我觉得我很接近(也许是渴望的想法),但每次运行程序时都会出现分段错误。从我的代码的外观来看,有没有人知道可能出了什么问题?
typedef struct Node {
char word[LENGTH+1];
struct Node *Next;
} Node;
hash_table_t *create_hash_table(int size)
hashtable = malloc(sizeof(hash_table_t));
if (hashtable == NULL)
{
return NULL;
}
hashtable->table= malloc(size* sizeof(struct Node *) ) ;
if (hashtable->table== NULL)
{
return NULL;
}
for(int i=0; i<size; i++)
{
hashtable->table[i]=NULL;
hashtable->size =size;
}
return hashtable;
typedef struct hash_table_t{
int size; /* the size of the table */
struct Node **table; /* the table elements */
} hash_table_t;
File *inptr;
Node* TempNode=NULL;
Node* new_node=NULL;
Node* Head=NULL;
char buffer[46];
unsigned int hashval;
int j=0;
int count=0;
int update_counter=0;
inptr= fopen(dictionary, "r");
if (inptr == NULL)
{
printf("Could not open dictionary file");
printf("\n");
return 0;
}
int ch = fgetc(inptr);
for ( ;; )
{
if ( ch == EOF ) //determines how many words are in the file
{
break;
}
if (isalpha(ch) || isdigit(ch) || ispunct(ch))
{
update_counter = 1;
}
if (isspace(ch) && update_counter )
{
count++;
update_counter = 0;
}
}
if (update_counter)
{
count++;
}
sizeOfDictionary=count;
rewind(inptr);
hashtable=create_hash_table(sizeOfDictionary);
while(fread(buffer,sizeof(buffer),1,inptr)!=0)
{
if(Head==NULL)
{
hashval = hash(buffer);
Head = malloc(sizeof(Node));
strcpy(&Head->word[j],buffer);
Head->Next = hashtable->table[hashval];
hashtable->table[hashval]=Head;
Head=Head->Next;
TempNode = Head;
}
else if(Head!=NULL)
{
new_node = malloc(sizeof(Node));
hashval = hash(buffer);
strcpy(&new_node->word[j],buffer);
new_node->Next = hashtable->table[hashval];
hashtable->table[hashval]=new_node;
TempNode=new_node->Next;
}
}
return true;