哈希表搭建

#include
#include
#include 
struct word
{
	int cp;
	char word[20];
};
struct lnode
{
	char word[20];
	int wordnum;
	struct lnode* next;
};
typedef struct lnode* list;
typedef struct lnode* position;
struct Tblnode
{
	int tablesize;
	list heads;
};
typedef struct Tblnode* HashTable;
struct word words[250000];
int compare(const void* x,const void* y)
{
	struct word* a;struct word* b;
	a=(struct word*)x;
	b=(struct word*)y;
	if(a->cp>b->cp) return -1;//a排在b前面;
	else if(a->cpcp) return 1;//b排在a前面
	else return strcmp(a->word,b->word);//strcmp函数比较两个字符串大小  a大于b返回正数 a小于b返回负数 
}
void print(int wordcount)
{
	int i; 
	for(i=0;i<=wordcount-1;i++) 
	{
		printf("%d:%s",words[i].cp,words[i].word);
		if(i!=wordcount-1) printf("\n");
	}
}
HashTable CreatTable(int size)
{
    HashTable na;
	na=(HashTable)malloc(sizeof(struct Tblnode));
	na->tablesize=size;
	na->heads=(list)malloc(sizeof(struct lnode)*na->tablesize);
	int i;
	//初始化头节点 
	for(i=0;i<=na->tablesize-1;i++) 
	{
	    na->heads[i].next=NULL; 
	} 
	return na;
}
int Hash(char* key)
{
	int H=0;
	while(*key!='\0')
	{
		H=(H<<5)+*key;
		*key++;
		H%=97;
	}
	return H;
}
position Find(HashTable na,char* key)
{
	int pos=Hash(key);
	//printf("pos=%d\n");
	list p_now=na->heads[pos].next;
	while(p_now!=NULL)
	{	
		if(strcmp(p_now->word,key)==0) return p_now;
		p_now=p_now->next;
	}
	return p_now;
}
HashTable InsertHashtable(HashTable na,char* key)
{
	//printf("before find\n");
	list p_find=Find(na,key);
	//printf("after find\n");
	if(p_find!=NULL) p_find->wordnum++;
	else
	{
		//创建新的结点 
		list p_next;
	    p_next=(list)malloc(sizeof(struct lnode));
    	strcpy(p_next->word,key);//一个字符指针就代表了一个字符串 
    	p_next->wordnum=1;p_next->next=NULL;
    	//创建新的位置
		int pos=Hash(key);//初始位置——头节点对应下标 
		//链表插在头节点后面就好啊!方便
		p_next->next=na->heads[pos].next ;
		na->heads[pos].next=p_next;
	}
	return na;
}
int main()
{
	char x;char zj[20];int zjnum=0;
	HashTable H;
	H=CreatTable(97);
	while(1)
	{
		scanf("%c",&x);
		if(x=='#') break;
		if(x>='A'&&x<='Z') x=x-'A'+'a';
		if(x>='a'&&x<='z'||x>='0'&&x<='9'||x=='_')
		{
			if(zjnum<=14)
			{
				zj[zjnum]=x;;
				zjnum++;
			}
		}
		else
		{
			if(zjnum!=0)
			{
		    	//printf("before insert\n");
				zj[zjnum]='\0';
		    	InsertHashtable(H,zj);
		    	zjnum=0;
		    	//printf("after insert\n");
			}
		}
	}
	int wordcount=0;int i;//count:多少个单词 num:一个单词多少个 
	for(i=0;i<=H->tablesize-1;i++)
	{
		list p_now=H->heads[i].next;
		while(p_now!=NULL)
		{
			strcpy(words[wordcount].word,p_now->word);
			words[wordcount].cp=p_now->wordnum;
			p_now=p_now->next;
			wordcount++;
		}
	}
	printf("%d\n",wordcount);
	qsort(words,wordcount,sizeof(words[0]),compare);
	print(wordcount/10);
}

你可能感兴趣的:(散列表,数据结构)