#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct Node{
int data;
struct Node *next;
};
struct HashTable{
struct Node **body;
int tableSize;
};
int nextPrime(int num){
num++;
int i;
while(1){
int q=sqrt(num);
for(i=2;i<=q;i++){
if(num%i==0){
break;
}
}
if(i>q){
return num;
}
num++;
}
}
struct HashTable *createTable(int size){
struct HashTable *H;
H=(struct HashTable *)malloc(sizeof(struct HashTable));
H->tableSize=nextPrime(size);
H->body=(struct Node **)malloc(sizeof(struct Node *)*H->tableSize);
for(int i=0;i<H->tableSize;i++){
H->body[i]=(struct Node *)malloc(sizeof(struct Node));
H->body[i]->next=NULL;
}
return H;
}
int Hash(int num,int size){
return num%size;
}
void Insert(struct HashTable *H,int num){
int pos;
pos=Hash(num,H->tableSize);
struct Node *p,*q;
p=H->body[pos];
while(p->next!=NULL){
if(p->next->data==num){
return;
}
p=p->next;
}
p=H->body[pos];
q=(struct Node *)malloc(sizeof(struct Node));
q->data=num;
q->next=p->next;
p->next=q;
}
void show(struct HashTable *H){
for(int i=0;i<H->tableSize;i++){
struct Node *p;
p=H->body[i]->next;
printf("第%d条链:",i);
while(p!=NULL){
printf("%3d",p->data);
p=p->next;
}
printf("\n");
}
}
void Delete(struct HashTable *H,int num){
int pos;
pos=Hash(num,H->tableSize);
struct Node *p,*q;
p=H->body[pos];
while(p->next!=NULL&&p->next->data!=num){
p=p->next;
}
if(p->next==NULL){
printf("There is not this num.\n");
}else{
q=p->next;
p->next=q->next;
free(q);
printf("delete %d successfully.\n",num);
}
}
int main(){
struct HashTable *H;
H=createTable(7);
for(int i=0;i<7;i++){
Insert(H,i+10);
Insert(H,i+20);
Insert(H,i+30);
}
printf("原哈希表:\n");
show(H);
printf("\n");
Delete(H,23);
Delete(H,36);
printf("\n删除节点后的哈希表:\n");
show(H);
return 0;
}
哈希表的实现(分离链表法,带头节点,C语言)
最新推荐文章于 2024-08-26 23:12:47 发布