【小镇的技术天梯】从头开始写算法,C语言hash表

【有时候数据结构和算法这种东西就是在时间和空间之间权衡,比如说当你想要维护一个自平衡的二叉树的时候就需要一个额外的指针,当你想要排序的时候,需要一个或者多个额外的空间来存储临时产生的数据一样。】

hash表,有时候也被称为散列表,可以理解成数据和hash表中整理的数据的多对一的关系,散列的规则可以自己随意定制,但是最佳的散列规则应该保证每个散列出来的数据组中的个数都应该存有差不多数量的数据。比如说1到100的数据中,我们可以按照%10的规则来散列,这样就可以保持每个散列组都有差不多8-9个的数据。

这个相对来说还是挺好理解的,hash表也用在了很多的地方,配合别的数据结构可以很好很高效地控制数据。

【下面提供个代码,看看就好,难度很简单】编译命令  gcc -o xxx zhash.c

/* 散列表实例 */


/*
 * author:镇天宇
 * 规则:%10散列
 */


#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

typedef struct Z_HASH_NODE
{
	int			data;
	struct Z_HASH_NODE	* next;
}hash_node;

typedef struct Z_HASH_TABLE
{
	hash_node* value[10];
}hash_table;


hash_table* create_hash_table()
{
	hash_table* chashtbl = (hash_table *) malloc( sizeof(hash_table) );
	memset( chashtbl, 0, sizeof(hash_table) );
	return(chashtbl);
}


hash_node* find_data_in_hash_table( hash_table* chashtbl, int data )
{
	hash_node* cnode;
	if ( chashtbl == NULL )
		return(NULL);

	if ( (cnode = chashtbl->value[data % 10]) == NULL )
		return(NULL);

	while ( cnode )
	{
		if ( data == cnode->data )
			return(cnode);
		cnode = cnode->next;
	}
	return(NULL);
}


int insert_data_into_hash( hash_table* chashtbl, int data )
{
	hash_node* cnode;
	if ( chashtbl == NULL )
		return(0);

	if ( (cnode = chashtbl->value[data % 10]) == NULL )
	{
		cnode = (hash_node *) malloc( sizeof(hash_node) );
		memset( cnode, 0, sizeof(cnode) );
		cnode->data			= data;
		chashtbl->value[data % 10]	= cnode;
		return(1);
	}

	while ( cnode->next != NULL )
		cnode = cnode->next;

	cnode->next = (hash_node *) malloc( sizeof(hash_node) );
	memset( cnode->next, 0, sizeof(hash_node) );
	cnode->next->data = data;
	return(1);
}

int delete_data_from_hash(hash_table* chashtbl,int data)
{
	hash_node* cnode;
	hash_node* chead;

	if(chashtbl==NULL||chashtbl->value[data%10]==NULL)
		return 0;

	if((cnode=find_data_in_hash_table(chashtbl,data))==NULL)
		return 0;

	if(cnode==chashtbl->value[data%10]){
		chashtbl->value[data%10]=cnode->next;			
		goto final;
	}

	chead=chashtbl->value[data%10];
	while(cnode!=chead->next)
		chead=chead->next;
	chead->next=cnode->next;

final:
	free(cnode);
	return 1;
}

/* 打印hash */
void print_hash_data( hash_table* chashtbl )
{
	int i; hash_node* cnode;
	for ( i = 0; i < 10; i++ )
	{
		if ( (cnode = chashtbl->value[i]) == NULL )
			continue;
		while ( cnode->next != NULL )
		{
			printf( "%d ", cnode->data );
			cnode = cnode->next;
		}
		printf("\n");
	}
}


int main()
{
	hash_table	* htbl = create_hash_table();
	int		i;
	for ( i = 0; i < 56; i++ )
	{
		insert_data_into_hash( htbl, i );
	}

	print_hash_data(htbl);
}




你可能感兴趣的:(【小镇的技术天梯】从头开始写算法,C语言hash表)