散列查找(分离链接法)

将相应位置上冲突的所有关键词存放在同一链表中

 1 #define KEYLENGTH 15
 2 typedef char ElementType[KEYLENGTH+1];
 3 typedef int Index;
 4 typedef struct LNode *ptrToLNode;
 5 struct LNode
 6 { 
 7     ElementType Data;
 8     ptrToLNode Next;
 9 };
10 typedef ptrToLNode Position;
11 typedef ptrToLNode list;
12 typedef struct Hashnode *HashTable;
13 
14 struct  Hashnode{
15     int TableSize;
16     list Heads;
17 };
18 HashTable CreateHash(int TableSize){
19     int i;
20     HashTable h;
21     h=(HashTable)malloc(sizeof(struct Hashnode));//申请哈希表空间
22     h->TableSize=TableSize;//哈希表空间大小
23     h->Heads=(list)malloc(TableSize* sizeof(struct LNode));//哈希表数组
24     for(i=0;i<TableSize;i++)//哈希表数组初始化
25     {
26         h->Heads[i].Data[0]='\0';   
27         h->Heads[i].Next=NULL;
28     }
29     return h;
30 }
31 Position Find(HashTable h,ElementType key)
32 {
33     Position p;
34     Index Pos;//哈希表数组下标
35     //Pos=Hash_char(key ,h->TableSize);//哈希函数
36     Pos=3;
37     p=h->Heads[Pos].Next;//从链表的第一个节点开始
38     while( p && strcmp(p->Data,key))//如果p不是空且key与data不相等
39         p=p->Next;//接着寻找下一个节点
40     return p;//没找到,最后返回空节点。找到了返回P
41 }
42 bool Insert(HashTable h ,ElementType key )
43 {
44     Position p,newcell;
45     Index Pos;//数组下标
46 
47     p=Find(h,key);//利用find函数看看key是否存在于原来的散列表中
48     if(!p){//如果P是空,表明key 不在散列表中,所以可以插入
49         newcell=(Position)malloc(sizeof(Position));//申请空间
50         strcpy(newcell->Data,key );//讲key拷贝到临时链表里
51         //Pos=Hash_char(key,h->TableSize);//算出数组下标
52         Pos=3;
53         newcell->Next=h->Heads[Pos].Next;//将newcell插入到链表的头部
54         h->Heads[Pos].Next=newcell;
55         return true;
56     }
57     else{
58         printf("error");
59         return false;
60     }
61 
62 }
63 void Destory(HashTable h )
64 {
65     int i;
66     Position p,temp;
67     for (i = 0; i < h->TableSize; i++)
68     {
69         p=h->Heads[i].Next;//p指向数组所对应的链表
70             while(p){             //p不是空就循环
71             temp=p->Next;       //
72             free(p);//从头部开始一个个free
73             p=temp;
74         }
75     }
76     free(h->Heads);
77     free(h);
78 
79 }
80 Index Hash_char(const char *key ,int TableSize)
81 {
82   unsigned int h =0;
83   while(*key !='\0')
84       h=(h<<5)+*key++;
85   return h%TableSize;
86 }

超级错误!!!!!!!!newcell=(Position)malloc(sizeof(Position));//申请空间

正确 newcell=(Position)malloc(sizeof(struct LNode));//申请空间

posted @ 2016-09-18 17:06  乐乐章  阅读(616)  评论(0编辑  收藏  举报