(1)初始化散列表;
(2)向散列表中插入一个元素;
(3)从散列表中删除一个元素;
(4)从散列表中查找一个元素。
#include <bits/stdc++.h>
#define ElemType int
#define HashSize 12
#define p 11
using namespace std;
//数据:19 14 23 1 68 20 84 27 55 11 10 79
typedef struct FLNode
{
//散列主文件中的节点类型
ElemType data; //值域
struct FLNode* next; //指向下一个节点的指针域
} HashNode;
int Hash(int key)
{
return key % p;
}
void InitHash(HashNode* H[])//初始化
{
int i, x;
int num[HashSize];
HashNode *h,*h1;
cout<<"请输入"<<HashSize<<"个数:";
for (i = 0; i < HashSize; i++)
{
cin >> num[i];
H[i] = new HashNode;
H[i]->data = i;
H[i]->next = NULL;
}
for (i = 0; i < HashSize; i++)
{
x = Hash(num[i]);
h=new HashNode;
h=H[x];
while(h->next)
{
h=h->next;
}//到达链尾
h1=new HashNode;
h1->data=num[i];
h1->next=NULL;
h->next=h1;
}
cout<<"初始化成功!"<<endl;
}
void PrintHash(HashNode *H[])//打印散列表
{
int i;
HashNode *h;
for (i = 0; i < HashSize; i++)
{
cout<<i<<":";
if (H[i]->next!=NULL)
{
h=new HashNode;
h=H[i];
while(h->next!=NULL)
{
cout<<h->next->data<<" ";
h=h->next;
}
}
cout<<endl;
}
system("pause");
}
void InsertHash(HashNode *H[])//插入
{
int x,y;
HashNode *h,*h1;
cout<<"请输入待插入数:";
cin>>x;
y=Hash(x);
h=new HashNode;
h=H[y];
while(h->next)
{
h=h->next;
}//到达链尾
h1=new HashNode;
h1->data=x;
h1->next=NULL;
h->next=h1;
cout<<"插入成功!"<<endl;
system("pause");
}
void DeleteHash(HashNode *H[])
{
int x,y;
HashNode *h1,*h;
cout<<"请输入待删除数:";
cin>>x;
y=Hash(x);
h=new HashNode;
h=H[y];
while(h->next)
{
h1=h;
h=h->next;
if(h->data==x)
{
h1->next=h->next;
cout<<"删除成功!"<<"\n";
system("pause");
return;
}
}//到达链尾
cout<<"删除失败! 未找到该数!"<<endl;
system("pause");
}
void FindHash(HashNode *H[])
{
int x,y;
HashNode *h;
cout<<"请输入待查找数:";
cin>>x;
y=Hash(x);
h=H[y];
while(h->next)
{
h=h->next;
if(h->data==x)
{
cout<<"找到"<<x<<" 属于:"<<y<<endl;
system("pause");
return;
}
}//到达链尾
cout<<"查找失败!未找到该数!"<<endl;
system("pause");
}
void PrintMenu()
{
cout<<" 【菜单】 \n";
cout<<"【1】-----初始化\n";
cout<<"【2】-----插入元素\n";
cout<<"【3】-----删除元素\n";
cout<<"【4】-----查找元素\n";
cout<<"【5】-----打印散列表\n";
cout<<"【0】-----退出\n";
cout<<"注:请先初始化再进行其他操作\n";
cout<<"请输入选择:";
}
void MenuHash(HashNode *H[])
{
int choice;
while(1)
{
PrintMenu();
cin>>choice;
switch(choice)
{
case 0:
return;
case 1:
InitHash(H);
system("pause");
system("cls");
break;
case 2:
InsertHash(H);
system("cls");
break;
case 3:
DeleteHash(H);
system("cls");
break;
case 4:
FindHash(H);
system("cls");
break;
case 5:
PrintHash(H);
system("cls");
break;
default:
cout<<"错误指令!"<<endl;
system("pause");
system("cls");
}
}
}
int main()
{
HashNode * H[HashSize];
MenuHash(H);
return 0;
}