《数据结构学习与实验指导》5-1:整数关键字的散列映射

来源:互联网 发布:ae圆点矩阵特效是哪个 编辑:程序博客网 时间:2024/06/02 04:59

实验内容:给定一系列整型关键字和素数PP,用除留余数法定义的散列函数将关键字映射到长度为PP的散列表中。用线性探测法解决冲突。
输入格式:输入第一行首先给出两个正整数N(N≤1000)和P(≥N的最小素数),分别为待插入的关键字总数以及散列表的长度。第二行给出N个整型关键字。数字间以空格分隔。
输出格式:在一行内输出每个整型关键字在散列表中的位置。数字间以空格分隔,但行末尾不得有多余空格。
测试用例:

输入 输入出 4 5
24 15 61 88 4 0 1 3 4 5
24 39 61 15 4 0 1 2 5 5
24 39 61 15 39 4 0 1 2 0
#include <stdio.h>#include <stdlib.h>typedef struct Node {    int value;    int choosed;} *PNode;typedef struct HashTable {    int size;    PNode arr;} *PHashTable;int N, P;int first = 1;PHashTable init();int hash(int key);int insert(PHashTable table, int key);int main() {    scanf("%d %d", &N, &P);    PHashTable table = init();    int i, key;    for (i = 0; i < N; i++) {        scanf("%d", &key);        int index = insert(table, key);        if (first) {            printf("%d", index);            first = 0;        } else {            printf(" %d", index);        }    }    return 0;} PHashTable init() {    PHashTable table = (PHashTable) malloc(sizeof(struct HashTable));    table->size = P;    table->arr = (PNode) malloc(sizeof(struct Node) * P);    int i;    for (i = 0; i < P; i++) {        table->arr[i].choosed = 0;    }    return table;}int hash(int key) {    return key % P;}int insert(PHashTable table, int key) {    int index = hash(key);    while (table->arr[index].choosed && table->arr[index].value != key) {        index++;        index = index % table->size;    }    if (! table->arr[index].choosed) {        table->arr[index].value = key;        table->arr[index].choosed = 1;    }    return index;}
阅读全文
0 0
原创粉丝点击