5-42 整型关键字的散列映射

来源:互联网 发布:淘宝联盟如何做推广 编辑:程序博客网 时间:2024/05/18 10:28

这里写图片描述

#include<stdio.h>#include<stdlib.h>struct node{    int data;    int flag;};struct hash{    int size;    struct node *cell;};typedef struct hash *HashTable;HashTable initial(int P){    HashTable H=malloc(sizeof(struct hash));    H->size=P;    H->cell=malloc(sizeof(struct node)*H->size);    while(P)    {        H->cell[--P].flag=-1;    }    return H;}int Hash(int key,int P){    return key%P;}int Find(int key,HashTable H){    int pos=Hash(key,H->size);    while((H->cell[pos].flag!=-1)&&(H->cell[pos].data!=key))    {        pos++;        if(pos==H->size)            pos=pos-H->size;    }    return pos;}void InsertAndOutput(int key,HashTable H){    int pos=Find(key,H);    if(H->cell[pos].flag==-1)    {        H->cell[pos].flag=0;        H->cell[pos].data=key;    }    printf("%d",pos);}main(){    int N,P,i,key;    HashTable H;    scanf("%d %d",&N,&P);    H=initial(P);    scanf("%d",&key);    InsertAndOutput(key,H);    for(i=1;i<N;i++)    {        scanf("%d",&key);        printf(" ");        InsertAndOutput(key,H);    }    printf("\n");}
0 0
原创粉丝点击