我是靠谱客的博主 天真黑米,最近开发中收集的这篇文章主要介绍算法与数据结构考研试题精析-第9章算法设计题40,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

已知哈希表装填因子小于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]='';
    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];
        }
    }
}

最后

以上就是天真黑米为你收集整理的算法与数据结构考研试题精析-第9章算法设计题40的全部内容,希望文章能够帮你解决算法与数据结构考研试题精析-第9章算法设计题40所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部