开散列法-拉链法的实现方式
#include<stdio.h>
#include<stdlib.h>
#define M 200
typedef struct node {
int pos;
struct node* link;
struct hashnode* branch;
}HashTableNode;
typedef struct hashnode {
int key;
struct hashnode* next;
}HashNode;
HashTableNode* NewHSTNode(int i) {
HashTableNode* htb;
htb = (HashTableNode*)malloc(sizeof(HashTableNode));
htb->pos = i;
htb->link = NULL;
htb->branch = NULL;
return htb;
}
HashNode* NewHashNode(int k) {
HashNode* p;
p= (HashNode*)malloc(sizeof(HashNode));
p->key = k;
p->next = NULL;
return p;
}
HashTableNode* CreateHashTable() {
int i;
HashTableNode* p, * r = NULL, * first=NULL;
for (i = 0; i < M;i++) {
p = NewHSTNode(i);
if (first!=NULL) {
r->link = p;
}
else {
first = p;
}
r = p;
}
return first;
}
void Search(HashTableNode* first, int k) {
int position;
HashNode * s;
s = (HashNode*)malloc(sizeof(HashNode));
position = k % M;
for (; first; first = first->link) {
if (first->pos == position) {
break;
}
}
if (first->branch == NULL) {
printf(“Find Nothing on %d\n”,k);
}
else {
s = first->branch;
while (s) {
if (s->keyk) {
printf(“find %d, position is: %d\n”,k,first->pos);
return;
}
else {
s = s->next;
}
}
printf(“Find Nothing on %d\n”, k);
}
}
void Insert(HashTableNode* first, int k) {
int position;
HashNode* p, s;
s = (HashNode)malloc(sizeof(HashNode));
p = NewHashNode(k);
position = k % M;
for (; first; first = first->link) {
if (first->posposition) {
break;
}
}
if(first->branch NULL) {
first->branch = p;
}
else {
s = first->branch;
while (s->next) {
s = s->next;
}
s->next = p;
}
}
void Delete(HashTableNode* first, int k) {
int position;
HashNode* s, p;
s = (HashNode)malloc(sizeof(HashNode));
p = (HashNode*)malloc(sizeof(HashNode));
position = k % M;
for (; first; first = first->link) {
if (first->pos == position) {
break;
}
}
if (first->branch == NULL) {
printf(“Find Nothing on %d, cannot delete!\n”, k);
}
else {
s = first->branch;
while (s) {
if (s->key == k) {
if (s first->branch) {
printf("find %d, position is: %d ", k, first->pos);
first->branch=s->next;
printf(“has been deleted!\n”);
free(s);
return;
}
else {
printf("find %d, position is: %d ", k, first->pos);
printf(“has been deleted!\n”);
p->next = s->next;
free(s);
return;
}
}
else {
p = s;
s = s->next;
}
}
printf("Find Nothing on %d, cannot delete!\n", k);
}
}
void PrintHashTable(HashTableNode* first) {
HashNode* s;
s = (HashNode*)malloc(sizeof(HashNode));
printf(“HashTable Content here: \n”);
for (; first; first = first->link) {
printf(“Position[%d]: “,first->pos);
if (first->branch!=NULL) {
s = first->branch;
while (s) {
printf(”%d “,s->key );
s = s->next;
}
}
printf(”\n”);
}
}
void main() {
HashTableNode* htb;
int i;
htb = CreateHashTable();
for (i = 0; i < 1000;i++) {
Insert(htb, i);
}
PrintHashTable(htb);
}