PTA数据结构与算法题目集(中文) 7-42整型关键字的散列映射 (25 分)
7-42 整型关键字的散列映射 (25 分)
给定一系列整型关键字和素数P,用除留余数法定义的散列函数将关键字映射到长度为P的散列表中。用线性探测法解决冲突。
输入格式:
输入第一行首先给出两个正整数N(≤)和P(≥的最小素数),分别为待插入的关键字总数、以及散列表的长度。第二行给出N个整型关键字。数字间以空格分隔。
输出格式:
在一行内输出每个整型关键字在散列表中的位置。数字间以空格分隔,但行末尾不得有多余空格。
输入样例:
4 5
24 15 61 88
输出样例:
4 0 1 3
题目分析:一道基本的散列表的题
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<math.h>
#define MAXTABLESIZE 100000
typedef enum{Legitimate,Empty,Deleted}EntryType;
typedef struct HashEntry Cell;
struct HashEntry
{
EntryType Type;
int Data;
}; typedef struct HblNode* HashTable;
struct HblNode
{
int TableSize;
Cell* Cells;
}; int Hash(int Data, int TableSize)
{
return Data % TableSize;
} int NextPrime(int N)
{
int P = (N % ) ? N : N + ;
for (; P < MAXTABLESIZE; P += )
{
int i = (int)sqrt(P);
for (; i > ; i--)
if (P % i == )
break;
if (i == )
break;
}
return P;
} HashTable CreateHashTable(int N)
{
int TableSize = NextPrime(N);
HashTable H = (HashTable)malloc(sizeof(struct HblNode));
H->TableSize = TableSize;
H->Cells = (Cell*)malloc(H->TableSize * sizeof(Cell));
for (int i = ; i < H->TableSize; i++)
H->Cells[i].Type = Empty;
return H;
} int Find(int Data, HashTable H)
{
int NewPos = Hash(Data, H->TableSize);
while (H->Cells[NewPos].Type!=Empty&&H->Cells[NewPos].Data!=Data)
{
NewPos++;
if (NewPos >= H->TableSize)
NewPos -= H->TableSize;
}
return NewPos;
} void Insert(int Data, HashTable H)
{
int Pos = Find(Data, H);
if (H->Cells[Pos].Type != Legitimate)
{
H->Cells[Pos].Data = Data;
H->Cells[Pos].Type = Legitimate;
}
} int main()
{
int N, P;
scanf("%d%d", &N, &P);
HashTable H = CreateHashTable(P);
int num;
for (int i = ; i < N-; i++)
{
scanf("%d", &num);
Insert(num,H);
printf("%d ", Find(num,H));
}
scanf("%d", &num);
Insert(num, H);
printf("%d", Find(num, H));
return ;
}