哈希表查找单词句子c语言
时间: 2023-10-26 09:36:50 浏览: 33
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LENGTH 50
#define MAX_SENTENCE_LENGTH 1000
#define TABLE_SIZE 100
struct Node {
char word[MAX_WORD_LENGTH];
struct Node* next;
};
struct HashTable {
struct Node* table[TABLE_SIZE];
};
int hash(char* word) {
int hash_value = 0;
int i = 0;
while (word[i] != '\0') {
hash_value += word[i];
i++;
}
return hash_value % TABLE_SIZE;
}
void insert(struct HashTable* hash_table, char* word) {
int index = hash(word);
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
strcpy(node->word, word);
node->next = hash_table->table[index];
hash_table->table[index] = node;
}
int search(struct HashTable* hash_table, char* word) {
int index = hash(word);
struct Node* current = hash_table->table[index];
while (current != NULL) {
if (strcmp(current->word, word) == 0) {
return 1;
}
current = current->next;
}
return 0;
}
int main() {
struct HashTable hash_table;
int i, j;
char sentence[MAX_SENTENCE_LENGTH];
char word[MAX_WORD_LENGTH];
for (i = 0; i < TABLE_SIZE; i++) {
hash_table.table[i] = NULL;
}
printf("Enter a sentence: ");
fgets(sentence, MAX_SENTENCE_LENGTH, stdin);
j = 0;
for (i = 0; sentence[i] != '\0'; i++) {
if (sentence[i] == ' ' || sentence[i] == '\n' || sentence[i] == '\r' || sentence[i] == '\t') {
word[j] = '\0';
if (strlen(word) > 0) {
if (!search(&hash_table, word)) {
insert(&hash_table, word);
}
}
j = 0;
} else {
word[j] = sentence[i];
j++;
}
}
printf("The unique words in the sentence are: ");
for (i = 0; i < TABLE_SIZE; i++) {
struct Node* current = hash_table.table[i];
while (current != NULL) {
printf("%s ", current->word);
current = current->next;
}
}
printf("\n");
return 0;
}