直接上代码
#include <iostream>
#include <cmath>
using namespace std;
#define MAX 100000
typedef int ElementType;
typedef int Index;
typedef Index Position;
typedef enum
{
Legitimate,
Empty,
Deleted
} EntryType;
typedef struct HashEntry Cell;
struct HashEntry
{
ElementType Data;
ElementType Info;
};
typedef struct TblNode *HashTable;
struct TblNode
{
int TableSize;
Cell *Cells;
};
int NextPrime(int N)
{
int p = (N % 2) ? N + 2 : N + 1;
while (p <= MAX)
{
int i;
for (i = (int)sqrt(p); i > 2; i--)
{
if (!(p % i))
break;
}
if (i == 2)
break;
else
p += 2;
}
return p;
}
HashTable CreateTable(int TableSize)
{
HashTable H;
H = (HashTable)malloc(sizeof(struct TblNode));
H->TableSize = NextPrime(TableSize);
H->Cells = (Cell *)malloc(H->TableSize * sizeof(Cell));
for (int i = 0; i < H->TableSize; i++)
H->Cells[i].Info = Empty;
return H;
}
Position Find(HashTable H, ElementType Key)
{
Position Currentpos, NewPos;
int CNum = 0;
int p = H->TableSize;
NewPos = Currentpos = Key % p;
while (H->Cells[NewPos].Info != Empty && H->Cells[NewPos].Data != Key)
{
if (++CNum % 2)
{
NewPos = Currentpos + ((CNum + 1) / 2) * ((CNum + 1) / 2);
if (NewPos >= H->TableSize)
NewPos = NewPos % H->TableSize;
}
else
{
NewPos = Currentpos - (CNum / 2) * (CNum / 2);
while (NewPos < 0)
NewPos += H->TableSize;
}
}
return NewPos;
}
bool Insert(HashTable H, ElementType Key)
{
Position Pos = Find(H, Key);
if (H->Cells[Pos].Info != Legitimate)
{
H->Cells[Pos].Info = Legitimate;
H->Cells[Pos].Data = Key;
return true;
}
else
{
cout << "键值已存在\n";
return false;
}
}
bool Delete(HashTable H, ElementType Key)
{
Position pos = Find(H, Key);
if (H->Cells[pos].Info == Empty || H->Cells[pos].Info == Deleted)
return false;
else if (H->Cells[pos].Info == Legitimate)
{
H->Cells[pos].Info = Deleted;
return true;
}
return true;
}
void PrintHashTable(HashTable H)
{
for (int i = 0; i < H->TableSize; i++)
{
if (H->Cells[i].Info == Legitimate)
cout << H->Cells[i].Data << ' ';
}
cout << "\n";
}
int main()
{
HashTable htb;
int N;
cin >> N;
htb = CreateTable(N);
ElementType x;
for (int i = 0; i < 5; i++)
{
cin >> x;
Insert(htb, x);
}
PrintHashTable(htb);
cin >> x;
cout << Delete(htb, x) << endl;
PrintHashTable(htb);
return 0;
}