链式哈希表分享
数据结构这玩意还是得静下心来学。最后哈希表输出节后会输出相同地址的表,这个没有处理。我想得是用快排先把指针地址传进去,排成有序的地址。然后想到地址穿进去,要考虑地址的长度。最后,想了下表是通过哈希值建立的,不能随意更改,不然会导致冲突。假如在一个哈希表中不存在冲突,即关键字和哈希表地址一一对应,实际复杂度(1),秒杀任何排序查找
如果存在冲突,O<n 所以说这执行效率极其高。在大数据中查找具有很大优势
程序代码:#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define HASHSIZE 101
#define WORDSIZE 30
struct Hlist
{
char *keyword;
char *def;
struct Hlist *next;
};
struct Hlist *hashtab[HASHSIZE]; /*哈希表指针数组,存放每个元素指向的表头*/
struct Hlist *install(char *, char *); /*创建哈希表*/
struct Hlist *find(char *); /*查找是否存在表中*/
char *setmalloc(char *); /*name和defn创建空间,便面之间赋值指向原来的地址*/
int getline(char *, int); /*简单的输入函数*/
unsigned hash(char *); /*哈希函数,根据用户自己的方法求哈希值,尽量很少冲突*/
int main()
{
int c, n, i = 0;
char name[WORDSIZE], def[WORDSIZE];
struct Hlist *p, *np[HASHSIZE];
printf("Please input keyword and difine numbrs\n");
scanf("%d", &n);
while ((c = getchar()) != EOF && c != '\n');
while (n-->0)
{
printf("Please input keyword\n");
getline(name, WORDSIZE);
printf("Please input define\n");
getline(def, WORDSIZE);
if (isalnum(*name) && isalnum(*def))
np[i++] = install(name, def); /*接收每次创建和修改的地址*/
else
printf("Please input make up word and digit \n");
}
n = i;
i = 0;
while (n-- > 0) { /*哈希表输出*/
for (; np[i] != NULL; np[i] = np[i]->next)
printf("%s %s\n", np[i]->keyword, np[i]->def);
++i;
}
}
struct Hlist *install(char *name, char *def)
{
struct Hlist *p;
unsigned hashval;
if ((p = find(name)) == NULL)
{
p = (struct Hlist *)malloc(sizeof(*p));
if (p == NULL || (p->keyword = setmalloc(name)) == NULL)
return NULL;
hashval = hash(name);
p->next = hashtab[hashval]; /*链表尾插法,链入到最开始指针数组的地址(即NULL)*/
hashtab[hashval] = p; //整个重点就是这两条代码
}
else
free(p->def);
if ((p->def = setmalloc(def)) == NULL)
return NULL;
return p;
}
char *setmalloc(char *s) /*开辟空间函数*/
{
char *p;
p = (char *)malloc(strlen(s) + 1);
if (p != NULL)
{
strcpy(p, s);
return p;
}
return NULL;
}
struct Hlist *find(char *s) /*查找函数*/
{
struct Hlist *p;
for (p = hashtab[hash(s)]; p != NULL; p = p->next)
if (!strcmp(s, p->keyword))
return p;
return NULL;
}
unsigned hash(char *s) /*得到哈希值函数(也就是keyword关键字值)*/
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % HASHSIZE;
}
程序代码:#include<stdio.h>
#include "Calc.h"
int getline(char *s, int limit)
{
int c, i;
i = 0;
while (--limit > 0 && (c = getchar()) != EOF && c != '\n')
{
s[i++] = c;
}
s[i] = '\0';
return i;
}[此贴子已经被作者于2017-5-19 08:33编辑过]










