// 哈希表的基本运算.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
typedef int KeyType;
const int NUM = 10;//0-9下表的数组用来存放不同索引值
#include
struct HashTable
{
KeyType key;
HashTable *next;
HashTable *head;//头结点
};
void Initial(KeyType a[],int n)//初始化数据
{
cout<<"请输入"<
for (int i = 0; i < n; i++)
{
cin>>a[i];
}
}
void CreateHT(HashTable ht[],KeyType a[],int n)//采用头插法建立哈希表
{
for (int i = 0; i < NUM; i++)
{
ht[i].head = new HashTable;
ht[i].head->next = NULL;//初始化数据
}
for (int i = 0; i < n; i++)//采用带有头结点的头插法
{
int n = a[i] % NUM;
//HashTable *head = new HashTable;
HashTable * p = new HashTable;
p->key = a[i];
p->next = ht[n].head->next;
ht[n].head->next = p;
//ht[n].head = head;
}
}
void display(HashTable ht[])//输出信息
{
for (int i = 0; i < NUM; i++)
{
cout<<"索引为"<的数据有:";
HashTable *p = ht[i].head->next;
while (p != NULL)
{
cout<
p = p->next;
}
cout<
}
}
void add(HashTable ht[],KeyType data)//插入数据
{
int n = data % NUM;
HashTable * p = new HashTable;
p->key = data;
p->next = ht[n].head->next;
ht[n].head->next = p;
}
int Remove(HashTable ht[],KeyType data)
{
int n = data % NUM;
HashTable *p = ht[n].head;
while (p != NULL)
{
HashTable *q = p;//q用来保存待删点的前一个点
p = p->next;
if(p->key == data)
{
if(p->next == NULL)//如果是所在索引表的最后一个元素
{
q->next = NULL;
}
else
{
q->next = p->next;
}
delete(p);
return 1;//删除成功
}
}
return 0;//删除失败
}
int _tmain(int argc, _TCHAR* argv[])
{
HashTable ht[NUM];
HashTable Test[NUM];
int n;
KeyType a[20];//假设数组长度不超过20
cout<<"请输入测试数组的个数(这里假设小于20):"<
cin>>n;
Initial(a,n);
CreateHT(ht,a,n);
cout<<"插入数据前,数据为:"<
display(ht);
add(ht,5);
cout<<"插入数据5之后,数据为:"<
display(ht);
cout<<"删除数据5之后,数据为:"<
Remove(ht,5);
display(ht);
return 0;
}