分離鏈接散列表

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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章