#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
typedef struct TangPoetry{
char name[50]; /* 诗的名称 */
char author[10]; /* 作者 */
char information[500]; /* 诗内容 */
char interpretation[500]; /* 释义 */
} ElementType;
typedef struct TblNode {
ElementType * Poretry;
int size;
} TblNode, *HashTable;
HashTable createTable(int tableSize) {
HashTable hashTable = (HashTable)malloc(sizeof(TblNode));
if (!hashTable) {
exit(EXIT_FAILURE);
}
hashTable->Poretry = (ElementType *)calloc(tableSize, sizeof(ElementType));
if (!hashTable->Poretry) {
free(hashTable);
exit(EXIT_FAILURE);
}
hashTable->size = tableSize;
return hashTable;
}
int getAddress(char name[], int tableSize) {
int i = 0;
int address = 0;
while (name[i] != '\0') {
address += name[i];
i++;
}
address = abs(address) % tableSize;
return address;
}
void insertTable(HashTable hashTable, ElementType item) {
int index = getAddress(item.name, hashTable->size);
strcpy(hashTable->Poretry[index].name, item.name);
strcpy(hashTable->Poretry[index].author, item.author);
strcpy(hashTable->Poretry[index].information, item.information);
strcpy(hashTable->Poretry[index].interpretation, item.interpretation);
}
void searchTable(HashTable hashTable, char name[]) {
int index = getAddress(name, hashTable->size);
ElementType *item = &hashTable->Poretry[index];
if (strcmp(item->name, name) == 0) {
printf("-------------------------------------------------------------------------------\n");
printf("诗名:%s\n作者:%s\n诗内容:%s\n释义:%s\n",
item->name, item->author, item->information, item->interpretation);
printf("-------------------------------------------------------------------------------\n");
} else {
printf("未找到诗名:%s\n", name);
}
}
int main() {
int tableSize = 10;
HashTable hashTable = createTable(tableSize);
ElementType item;
int num;
printf("请输入要插入的诗的个数:");
scanf("%d", &num);
int i;
for (i = 0; i < num; i++) {
printf("请输入诗名:");
scanf(" %s", item.name);
printf("请输入诗的作者:");
scanf(" %s", item.author);
printf("请输入诗的内容:");
scanf(" %[^\n]", item.information);
printf("请输入诗的释义:");
scanf(" %[^\n]", item.interpretation);
insertTable(hashTable, item);
}
char name[50];
printf("请输入要查找的诗名:");
scanf(" %s", name);
searchTable(hashTable, name);
double a;
a=1.0*num/tableSize;
printf("%.2f",a);
free(hashTable->Poretry);
free(hashTable);
return 0;
}
散列表实现唐诗
最新推荐文章于 2024-08-18 12:51:45 发布