#include<iostream>
using namespace std;
#define M 5
//定義數據類型
typedef int ElemType ;
//定義哈希表上掛的鏈表的結點
typedef struct Node
{
ElemType data;
struct Node *next;
}Node,*pNode;
//定義哈希表上的表槽
typedef struct HashNode
{
pNode first;//指向鏈表的第一個結點
}HashNode,*HashTable;
//創建一個具有n個表槽的哈希表
HashTable create_HashTable(int n)
{
HashTable hashtable=(HashTable)malloc(n*sizeof(HashNode));
if(!hashtable)
{
cout<<"哈希表分配空間失敗"<<endl;
exit(-1);
}
for(int i=0;i<n;i++)
{
hashtable[i].first=NULL;
}
return hashtable;
}
pNode search_HashTable(HashTable hashtable, ElemType data)
{
pNode p;
p=hashtable[data%M].first;
if(!p)
return NULL;
else if(p->data==data)
return p;
while(p->next&&p->next->data!=data)
{
p=p->next;
}
return p->next;
}
bool insert_HashTable(HashTable hashtable,ElemType data)
{
pNode p,pNew;
if(search_HashTable(hashtable,data))
return false;
else
{
pNew=(pNode)malloc(sizeof(Node));
pNew->data=data;
pNew->next=NULL;
p=hashtable[data%M].first;
if(!p)
{
hashtable[data%M].first=pNew;
}else{
while(p->next)
p=p->next;
p->next=pNew;
}
}
return true;
}
bool delete_HashTable(HashTable hashtable,ElemType data)
{
if(!search_HashTable(hashtable,data))
return false;
pNode p,q;
p=hashtable[data%M].first;
if(p->data==data)
{
hashtable[data%M].first=p->next;
free(p);
}
else
{
while(p->data!=data)
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
return true;
}
void destroy_HashTable(HashTable hashtable,int n)
{
for(int i=0;i<n;i++)
{
pNode p=hashtable[i].first;
pNode q;
while(p)
{
q=p;
p=p->next;
free(q);
q=0;
}
}
free(hashtable);
hashtable=0;
}
void main()
{
//創建一個具有n個表槽的哈希表
HashTable hashtable;
hashtable=create_HashTable(6);
if(insert_HashTable(hashtable,1))
cout<<"插入元素1成功"<<endl;
if(insert_HashTable(hashtable,6))
cout<<"插入元素6成功"<<endl;
cout<<"輸出插入的元素"<<hashtable[1].first->data<<hashtable[1].first->next->data<<endl;
cout<<"請輸入要查詢的元素"<<endl;
if(search_HashTable(hashtable,1))
cout<<"查詢成功"<<endl;
else{
cout<<"查詢失敗"<<endl;
}
if(search_HashTable(hashtable,6))
cout<<"查詢成功"<<endl;
else{
cout<<"查詢失敗"<<endl;
}
if(delete_HashTable(hashtable,6))
cout<<"刪除6成功"<<endl;
else
cout<<"刪除6失敗"<<endl;
if(search_HashTable(hashtable,6))
cout<<"查詢成功"<<endl;
else{
cout<<"查詢失敗"<<endl;
}
destroy_HashTable(hashtable,6);
cout<<"銷燬成功"<<endl;
system("pause");
}
哈希表的創建查詢插入刪除銷燬
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.