山东大学数据结构实验报告四
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
大学软件工程学院
数据结构课程实验报告
using namespace std;
class ChainHashTable
{
public:
ChainHashTable(int divisor);
~ChainHashTable();
bool Insert(int k);
bool Search(int k);
void print();
private:
int d;
ChainHashTableNode *ht;
};
ChainHashTableNode.cpp
#include"ChainHashTable.h"
#include
using namespace std;
ChainHashTable::ChainHashTable(int divisor) {
d = divisor;
ht = new ChainHashTableNode[d];
}
bool ChainHashTable::Insert(int k)
{
int j = k%d;
if (ht[j].Insert(k))
{
return true;
}
else{
return false;
}
}
void ChainHashTable::print()
{
for (int i = 0; i < d; i++)
{
ht[i].print();
}
}
ChainHashTableNode.h
#pragma once
#include"Node.h"
class ChainHashTableNode
{
public:
ChainHashTableNode();
bool Insert(int k);
bool Search(int k);
void print();
private:
Node *first;
};
ChainHashTableNode.cpp
#include"ChainHashTableNode.h"
#include
using namespace std; ChainHashTableNode::ChainHashTableNode() {
first = 0;
}
bool ChainHashTableNode::Search(int k) {
if (first == 0) return false;
Node *current = first;
while (current)
{
if (current->value == k)
{
return true;
}
current = current->link;
if (current)
{
if (current->value == k)
{
return true;
}
}
}
return false;
}
bool ChainHashTableNode::Insert(int k) {
if (Search(k))
{
cout << "已经存在此元素" << endl;
return false;
}
else {
Node *p = new Node();
p->value = k;
if (first == 0)
{
first = p;
return true;
}
else
{
p->link = first;
first = p;
return true;
}
}
}
void ChainHashTableNode::print()
{
Node *current = first;
if (first)
{
while (first)
{
cout << first->value << " ";
first = first->link;
}
cout << endl;
first = current;
}
else {
cout << -1 << endl;
}
}
HashTable.h
#pragma once
class HashTable
{
public:
HashTable(int divisor);
~HashTable();
int Search(int k);//搜索算法
bool Insert(int e);
void print();
private:
int hSearch(int k);
int d;//除数
int *ht;//桶,大小取决于d就是除数是多少
bool *empty;//一维数组,用来存储第I个桶是否存入了元素};
HashTable.cpp
#include"HashTable.h"
#include
using namespace std;
HashTable::HashTable(int divisor)
{
d = divisor;
ht = new int[d];
empty = new bool[d];
for (int i = 0; i < d; i++)
{
empty[i] = true;
ht[i] = 0;
}
}
HashTable::~HashTable()
{
delete[]ht;
delete[]empty;
}
int HashTable::hSearch(int k)//搜索值为K的元素
{
int i = k%d;
int j = i;
do{
if (ht[j] == k || empty[j]) return j;
j = (j + 1) % d;
} while (j != i);
return j;
}