链接法解决冲突】利用链接法来解决冲突的散列表

~~~~(>_<)~~~~,,搞了好几天终于把这个做出来了。。

首先看一下这种散列表的结构:

1.每个槽都令其为NULL,注意里面保存的都是指向Node的指针,而不是结点哦~

2.然后我这里把链表的头结点,比如上图的k1,k5,k8的prior指针指向了T这个散列表,因为这样删除的时候会比较简单。

3.注意删除链表中的第一个结点和尾结点时候的不同方法哦。

好了,代码如下:

#include<stdio.h>#include<stdlib.h>typedef struct Node{int key;Node *prior;Node *next;}Node;typedef struct t{Node *firstarc;//利用指针数组}T[100];typedef struct Hash{T hash;int size;}Hash;Hash * Hash_create(){Hash *HashTable=(Hash *)malloc(sizeof(Hash));printf("关键字全域U是多少?\n");scanf("%d",&HashTable->size);for(int i=0;i<HashTable->size;i++)HashTable->hash[i].firstarc=NULL;//如果为T[]数组可以这么用,如果是指针不可以这么用return HashTable;}void DIRECT_SEARCH_INSERT(Hash *HashTable,Node *node){Node *p=(Node *)malloc(sizeof(Node));p=HashTable->hash[node->key%HashTable->size].firstarc;if(p==NULL){HashTable->hash[node->key%HashTable->size].firstarc=node;node->prior=HashTable->hash[node->key%HashTable->size].firstarc;node->next=NULL;}else{Node *temp=(Node *)malloc(sizeof(Node));temp->key=node->key;temp->next=p;p->prior=temp;temp->prior=HashTable->hash[node->key%HashTable->size].firstarc;HashTable->hash[node->key%HashTable->size].firstarc=temp;}}void DIRECT_SEARCH_DELETE(Hash* HashTable,int key){Node *p=HashTable->hash[key%HashTable->size].firstarc;int i=1;while(p->next!=NULL){if(p->key==key){p->prior->next=p->next;p->next->prior=p->prior;//free(p);break;}p=p->next;i++;}if(p->next==NULL&&i==1){if(p->key==key){HashTable->hash[key%HashTable->size].firstarc=NULL;//free(p);}}if(p->next==NULL&&i!=1){if(p->key==key){p->prior->next=NULL; }}if(p->next==NULL){if(p->key!=key) printf("不存在这个值!\n");}}void DIRECT_SEARCH_Search(Hash *HashTable,int key){int i=1;Node *p=HashTable->hash[key%HashTable->size].firstarc;if(p==NULL){ printf("不存在这个值!\n"); return;}while(p->next!=NULL){if(p->key==key){printf("存在key=%d这个值,放在table[%d]这个链表的第%d个位置上\n",key,key%HashTable->size,i);break;}p=p->next;i++;}if(p->next==NULL){if(p->key==key)printf("存在key=%d这个值,放在table[%d]这个链表的第%d个位置上\n",key,key%HashTable->size,i);elseprintf("不存在这个值\n");}}

int main(void)

{ int key;Hash *HashTable=(Hash *)malloc(sizeof(Hash));HashTable=Hash_create();printf("请输入一些数值,以#结束\n");int ch;while(scanf("%d",&ch)==1){Node *node=(Node *)malloc(sizeof(node));node->key=ch;node->prior=node->next=NULL;//printf("node->key=%d",node->key);DIRECT_SEARCH_INSERT(HashTable,node);}//while(1)//{//printf("您要查找多少:");//fflush(stdin);//scanf("%d",&key);//DIRECT_SEARCH_Search(HashTable,key);//}while(1){printf("您要查找多少:");fflush(stdin);scanf("%d",&key);DIRECT_SEARCH_Search(HashTable,key);printf("您要删除多少:");fflush(stdin);scanf("%d",&key);DIRECT_SEARCH_DELETE(HashTable,key);}

结果展示:

而消极的人则在每个机会都看到某种忧患。

链接法解决冲突】利用链接法来解决冲突的散列表

相关文章:

你感兴趣的文章:

标签云: