分离链接散列表

1、原理

暂时略,先贴代码

2、代码

(1)main.cpp

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+	分离链接散列表(C版)
+
+
+author:zhouyong							2013-3-4 19:03
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#include <stdio.h>
#include "hashsep.h"


int main()
{
	HashTable hashtbl;
	hashtbl=InitTable(10);
	int a[]={12,22,32,14,24,17,23,25,36,39};
	int i;
	for (i=0;i<10;i++)
	{
		Insert(a[i],hashtbl);
	}
	
	return 0;
}
(2)hashsep.h

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+	分离链接散列表(C版)头文件
+
+
+author:zhouyong							2013-3-4 19:03
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifndef _HashSep_H
#define _HashSep_H

#define MinTableSize 5;
struct ListNode;
typedef int ElementType;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;

HashTable InitTable(int TableSize);
int Hash(ElementType Key,int TableSize);
void DestroyTable(HashTable H);
Position Find(ElementType Key,HashTable H);
void Insert(ElementType Key,HashTable H);
ElementType Retrieve(Position P);

struct ListNode
{
	ElementType Element;
	Position Next;
};

typedef Position List;

struct HashTbl
{
	int TableSize;
	List *TheLists;	//指向指针的指针
};

#endif

(3)hashsep.c

#include <stdio.h>
#include <stdlib.h>
#include "hashsep.h"

HashTable InitTable(int TableSize)
{
	HashTable H;
	int i;
	/*
	if(TableSize<MinTableSize)
	{
		printf("Table size too small");
		return NULL;
	}
	*/
	H=(HashTable)malloc(sizeof(struct HashTbl));
	if(H==NULL)
		printf("Out of space!");
	H->TableSize=TableSize;
	H->TheLists=(List *)malloc(sizeof(List)*H->TableSize);
	if(H->TheLists==NULL)
		printf("Out of space !");
	for (i=0;i<H->TableSize;i++)
	{
		H->TheLists[i]=(List)malloc(sizeof(struct ListNode));
		if(H->TheLists[i]==NULL)
			printf("Out of space!");
		else
			H->TheLists[i]->Next=NULL;
	}
	return H;
}

Position Find(ElementType Key,HashTable H)
{
	Position P;
	List L;
	L=H->TheLists[Hash(Key,H->TableSize)];
	P=L->Next;
	while(P!=NULL&&P->Element!=Key)
		P=P->Next;
	return P;
}

void Insert(ElementType Key,HashTable H)
{
	Position Pos,NewCell;
	List L;
	Pos=Find(Key,H);
	if(Pos==NULL)
	{
		NewCell=(List)malloc(sizeof(struct ListNode));
		if(NewCell==NULL)
			printf("Out of space !");
		else
		{
			L=H->TheLists[Hash(Key,H->TableSize)];
			NewCell->Next=L->Next;
			NewCell->Element=Key;
			L->Next=NewCell;
		}
	}
}

int Hash(ElementType Key,int TableSize)
{
	return Key%TableSize;
}


发布了35 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ZHOUYONGXYZ/article/details/8805355