Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

路过~~~,一个链地址哈希,正好昨天想复习数据结构,顺别写个自己的哈希以后能用,咱也来试试咋样,,凑合吧,本来也不是为acm写的,简单改了一下,有望指点,c++编译没问题

Posted by ZHANG1 at 2017-01-20 02:59:11 on Problem 2503
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Node
{
	char  key[11];
	char value[11];
	Node*next;
};
struct Table
{
	Node*table;
	int range;
};
int Insert(Node*Head,Node*ele);			//插入结点
int InitTable(int range,Table*table);  //初始化哈希表
unsigned long CalcHash(char*key);
int In(Table*table,char*key,char*value);
char* Find(Node*Head,char*key);
char*Out(Table*table,char*key);
int Insert(Node*Head,Node*ele)
{
	while(Head->next!=NULL)
	{
		Head=Head->next;
		//if(strcmp(ele->key,Head->key)==0)
		//{
		//	return 0;
		//}
	}
	Head->next=ele;
	return 1;
};
unsigned long CalcHash(char*key)
{
	int length=strlen(key);
	unsigned long Hash=0;
	for(int i=0;i<length;i++)
	{
		Hash=(key[i]<<3)+(key[i]>>3)+Hash+(key[i]<<(i%6-6));
	}
	return Hash;
}
int InitTable(int range,Table*table)
{
	table->table=(Node*)malloc(range*sizeof(Node));   //申请空间
	table->range=range;
	memset(table->table,0,range*sizeof(Node));
	/*
	for(int i=0;i<range;i++)//初始化结点
	{
		table->table[i].next=NULL;
	}*/
	return 0;
}
int In(Table*table,char*key,char*value)
{
	unsigned long Hash=CalcHash(key)%table->range;  //计算散列表的位置
	//Node*ele=new Node;
	Node*ele=(Node*)malloc(sizeof(Node));
	memcpy(ele->key,key,11);  //创造结点
	memcpy(ele->value,value,11);
	ele->next=NULL;
	Insert(&(table->table[Hash]),ele);
	/*if(Insert(&(table->table[hash]),ele)==0) //插入结点成功
	{
		//cout<<"SUCCESS"<<endl;
		return 1;
	}
	else
	{
		//cout<<"FAILD"<<endl;
		return 0;
	}*/
	return 0;
}
char* Find(Node*Head,char*key)
{
	while(Head->next!=NULL)
	{
		Head=Head->next;
		if(strcmp(key,Head->key)==0)
		{
			return Head->value;
		}
	}
	return NULL;
}
char*Out(Table*table,char*key)
{
	unsigned long Hash=CalcHash(key)%table->range;  //计算散列表的位置
	return  Find(&(table->table[Hash]),key);
}
char buffer[22];
int main()
{
	char key[11],value[11];
	char*outs;
	Table t;
	InitTable(10001,&t);
	while(gets(buffer))
	{
	    if(buffer[0] == '\0')	break;
		sscanf(buffer, "%s %s", value, key);
		In(&t,key,value);

	}
	while(scanf("%s",key)!=EOF)
	{
		outs=Out(&t,key);
		if(!outs)
            printf("eh\n");
		else
            printf("%s\n",outs);
	}
	return 0;
}


Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator