hash表建立 很久没写数据结构了

/**
auhtor:lx
date 4.9 2011
brief hash table
*/

#include
<stdio.h>
#include
<stdlib.h>
#include
<stdbool.h>
#define hash_num 5

typedef
char Bool;

struct hash_node
{
int date; /*结点值*/
struct hash_node *next; /*下一个节点*/
Bool found;
};

struct hash_node* hash_table[hash_num]; /*存储hash table 所有信息*/

void hash_table_found( int value )
{
int hash;
hash
= value % hash_num;

/* 建立结点 */
struct hash_node* node = (struct hash_node*)malloc( sizeof( struct hash_node) );
node
->date = value;
node
->next = NULL;
node
->found = 't';

if ( hash_table[ hash ]->found == 'f' )
{
hash_table[ hash ]
->date = value;
hash_table[ hash ]
->next = NULL;
hash_table[ hash ]
->found = 't';
}
else
{
node
->next = hash_table[ hash ];
hash_table[ hash ]
= node;
}

}
void hash_table_output()
{
int i = 0;

for ( ; i < hash_num; i++ )
{
if ( hash_table[i]->found == 't' )
{
while ( hash_table[i] != NULL )
{
printf(
"%d\t", hash_table[i]->date );
hash_table[i]
= hash_table[i]->next;
}

printf(
"\n" );
}
}
}

int main( void )
{
/*要放入hash表的数据*/
int a[10] = { 0, 0, 400, 20, 12, 450, 2222, 30, 1 , 200 };

int j;
for ( j = 0; j < hash_num; j++ )
{
hash_table[j]
= ( struct hash_node* )malloc( sizeof( struct hash_node ) );
hash_table[j]
->date = 0;
hash_table[j]
->next = NULL;
hash_table[j]
->found = 'f';

}

int i = 0;
for ( ; i < 10; i++ )
{
hash_table_found( a[i] );
}

hash_table_output();
}
posted @ 2011-04-09 16:12  lxgeek  阅读(349)  评论(0编辑  收藏  举报