⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 哈希表gai.cpp

📁 数据结构课程设计
💻 CPP
字号:
#include <iostream>
#include<string>
#include<fstream>
#define m 5   //表长
#define y 3    //小于等于mde 最大素数
//#define NULLKEY  #  
//代表空记录的关键字值
using namespace std;


typedef struct
{
	string name;
	string sex;
	int age;
}RecordType;

typedef RecordType HashTable[m];
//哈希查找函数
int HashSearch(HashTable ht,string K)
{   
	int h0,hi;
	h0=(K[0]-96)%y;
	if(ht[h0].name=="#")
	{
		return(-1);
	}
	else
	{
		if(ht[h0].name==K)
		{
			return(h0);
		}
		else
		{
			for(int i=1;i<=m-1;i++)
			{
				hi=(h0+i)%m;
				if(ht[hi].name=="#")
				{
					return(-1);
				}
				else
				{
					if(ht[hi].name==K)
					{
						return(hi);
					}
				}
			}
			return (-1);
		}
	}
}




//创建哈希表
void HashCreate(HashTable & ht)
{
     //将文件中信息读出
	ifstream in("hash.txt");
	string s,t;
	int ia,h0,hi;
	RecordType p;
	

	for(int i=0;i<3&&s!="#";i++)
	{
		in>>s>>t>>ia;
	//	if(s="#")break;
		
		p.name=s;
		p.sex=t;
		p.age=ia;

		h0=(s[0]-96)%y;//哈希函数
		if(ht[h0].name=="#")
		{
			ht[h0]=p;
		}
         else
		 {
			 for(int i=0;i<=m-1;i++)
			 {
				 hi=(h0+i)%m;
				 if(ht[hi].name=="#")
				 {
					 ht[hi]=p;
					 break;        //注意此处
				 }
			 }
		 }
	}
}


//打印哈希表
void HashPrint(HashTable  ht)
{
	cout<<"name "<<"sex "<<"age  "<<endl;    
	for(int i=0;i<m;i++)
	{
		if(ht[i].name!="#")
		cout<<ht[i].name<<"  "<<ht[i].sex<<" "<<ht[i].age<<endl;
		else
			cout<<"空元素"<<endl;
	}
}

		

void main()
{
    RecordType hata[m];
	

	//初始化哈希表
    for(int i=0;i<m;i++)
	{
		hata[i].name="#";
	}
  //  HashPrint(hata);

	HashCreate(hata);


	cout<<"输出创建好的哈希表:"<<endl;
	HashPrint(hata);

	//查找元素
    cout<<"输入要查找的姓名:"<<endl;
	string str;
	cin>>str;
     int t=HashSearch(hata,str);
	if(t!=-1)
	{
		cout<<"查找成功!"<<endl;
		
		cout<<hata[t].name<<"  "<<hata[t].sex<<"  "<<hata[t].age<<endl;
	}
	else
	{
		cout<<"查找失败!"<<endl;
	}
}

	


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -