// HashTable.cpp : 定義控制檯應用程序的入口點
//哈希表的實現
//哈希函數採用除留餘數法構造
//使用鏈地址法解決衝突
#include "stdafx.h"
#include <iostream>
using namespace std;
const int MAXSIZE = 100;
int a[MAXSIZE];
//哈希表的結點類型
class HashNode
{
public:
HashNode():next(NULL){};//默認構造函數
HashNode(int item):data(item), next(NULL){};//一般構造函數
private:
int data;
HashNode *next;
friend class HashTable;
};
//哈希表類型
class HashTable
{
public:
HashTable();
void Create(int *a, int n);//創建哈希表
bool Find(int data);//查找
void Insert(int data);//插入
void Delete(int data);//刪除
private:
HashNode *value[10];//哈希表長度爲10
};
HashTable::HashTable()//默認構造函數
{
memset(value, NULL, 10*sizeof(HashNode*));
}
void HashTable::Create(int *a, int n)
{
cout << "請輸入n個元素:" << endl;
for (int i=0; i<n; i++)
{
cin >> a[i];
Insert(a[i]);
}
}
bool HashTable::Find(int data)
{
HashNode *pNode = NULL;
if (value[data%10] == NULL)//該結點不存在,則返回false
{
return false;
}
pNode = value[data%10];//獲取所在位置對應的鏈表的第一個結點
while(pNode ->next != NULL && pNode->data != data)
{
pNode = pNode->next;
}
if (pNode != NULL)
{
return true;
}
else
{
return false;
}
}
void HashTable::Insert(int data)
{
HashNode *pNode = NULL;
if (value[data%10] == NULL)//獲取所在位置對應的鏈表爲空,則插入
{
pNode = new HashNode;
pNode->data = data;
value[data%10] = pNode;
}
else//所在位置對應的鏈表不空
{
if (Find(data))//檢查該數值是否已經存在,若存在則返回
{
return;
}
else//否則插入鏈表尾端
{
pNode = value[data%10];
while(pNode->next != NULL)
{
pNode = pNode->next;
}
HashNode *newNode = new HashNode(data);
pNode->next = newNode;
}
}
}
void HashTable::Delete(int data)
{
HashNode *pNode = NULL;//定位到待刪除的結點
HashNode *pPre = NULL;//定位到待刪除結點的前一個結點
if (!Find(data))
{
cout << "該數值的結點不存在!" << endl;
}
else
{
pNode = value[data%10];//初始值爲所在位置對應的鏈表的第一個結點
if(pNode->data == data)//頭結點即爲待刪除的結點
{
value[data%10] = pNode->next;
cout << data << "刪除成功!" << endl;
}
else//否則指針後移,找到待刪除的結點
{
pPre = pNode;
while(pNode->next != NULL && pNode->next->data != data)
{
pPre = pNode;
pNode = pNode->next;
}
pPre->next = pNode->next;
delete pNode;
pNode = NULL;
cout << data << "刪除成功!" << endl;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n = 0;
cout << "請輸入哈希表元素的個數:";
cin >> n;
HashTable *ht = new HashTable;
ht->Create(a, n);
cout << ht->Find(9) << endl;
cout << ht->Find(3) << endl;
ht->Delete(10);
ht->Delete(8);
cout << ht->Find(8) << endl;
system("pause");
return 0;
}