算法与数据结构考研试题精析-第9章算法设计题40

本文聚焦于哈希表在考研试题中的应用,讲解了当装填因子小于1且采用线性探测开放地址法处理冲突时,如何设计一个程序,按字母顺序输出所有关键字。内容涉及哈希函数设计与冲突解决策略。
摘要由CSDN通过智能技术生成

已知哈希表装填因子小于1,哈希函数为关键字第一个字母在字母表中的序号,处理冲突的方法为线性探测开放地址法,编写一个按第一个字母的顺序输出哈希表中所有关键字的程序。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define m 29
#define MAXSIZE 20
#define SUCCESS 1
#define UNSUCCESS 0
#define DUPLICATE -1

typedef int Status;
typedef struct
{
    char s[MAXSIZE];
}String;
typedef struct
{
    String H[m];
    int num;
}HashTable;

int Hash(String s);
void Collision(int *p,int c);
Status SearchHash(HashTable T,String k,int *p,int *c);
Status InsertHash(HashTable *T,String e);
void Output(HashTable T);

int main()
{
    HashTable T;
	int i;
	for(i=0;i<m;i++)
		T.H[i].s[0]='\0';
    T.num=0;
    String e;
    printf("Input the keys to create the HashTable:");
    scanf("%s",e.s);
	i=Hash(e);
    while(i>=0 && i<27)
    {
        InsertHash(&T,e);
        printf("Input the keys to create the HashTable--0 to quit:");
        scanf("%s",e.s);
		i=Hash(e);
    }
    Output(T);

    return 0;
}
int Hash(String s)
{
    int t;
    char c;
    c=toupper(s.s[0]);
    t=(int)(c-'A');
    return t;
}
void Collision(int *p,int c)
{
    *p=((*p)+1)%m;
}
Status SearchHash(HashTable T,String k,int *p,int *c)
{
    *p=Hash(k);
    while(*c<m && T.H[*p].s[0] && strcmp(T.H[*p].s,k.s))
        Collision(p,++(*c));
    if(!strcmp(T.H[*p].s,k.s))
        return SUCCESS;
    else
        return UNSUCCESS;
}
Status InsertHash(HashTable *T,String e)
{
    int p;
    int c=0;
    if(SearchHash(*T,e,&p,&c))
    {
        printf("There is already %s at H[%d]\n",e.s,p);
        return DUPLICATE;
    }
    else if(c==m)
    {
        printf("The Table is full!\n");
        return UNSUCCESS;
    }
    else
    {
        T->H[p]=e;
        T->num++;
        printf("Done!\n");
        printf("There are %d numbers in the Table.\n",T->num);
        return SUCCESS;
    }
}
void Output(HashTable T)
{
    int i;
    for(i=0;i<26;i++)
    {
        String a;
        int n=0;
        a=T.H[i];
        while(a.s[0])
        {
            int t;
            t=Hash(a);
            if(i==t)
                printf("%s ",a.s);
            a=T.H[(++n+i)%m];
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值