Hash基本操作

//结构定义
#define HASHNUM 13

typedef  unsigned  int KeyType;
typedef  struct  {}DataType;

typedef  struct  HashNode
{
	KeyType  key;
	DataType  data;
	HashNode  *next;
}HashNode ;

typedef  struct  Hash
{
	HashNode *hashTable[HASHNUM];
}Hash;
//初始化
void InitHash(MyHash *hash)
{
	if(hash == NULL)  exit(0);

	for(int i ; i<HASHNUM ; ++i)
	{
		hash->hashTable[i] = NULL;
	}
}
//哈希函数  散列函数
static int Hash(KeyType key)
{
	return key % HASHNUM;
}
//寻找
static int SearchNot(MyHash *hash , KeyType key , int pos)
{
	HashNode *p = hash ->hashTable[pos];

	while(p != NULL)
	{
		if(p->key == key)
		{
			return 0;
		}
		p = p->next;
	}
	return 1;
}
HashNode *Search(MyHash *hash , KeyType key)
{
	if(hash == NULL)  exit(0);

	HashNode *p = hash->hashTable[Hash(key)];

	while(p != NULL)
	{
		if(p->key == key)
		{
			return p;
		}
		p = p->next;
	}
	return NULL;
}
//创建新结点
static HashNode *_ApplyNode(KeyType key , HashNode *next)
{
	HashNode *s = (HashNode *)malloc(sizeof(HashNode ));

	if(s == NULL)  exit(0);
	s->key = key;
	s->next = next;

	return 0;
}
//插入
void  InterHash(MyHash *hash , KeyType key )
{
	if(hash == NULL)  exit(0);

	int pos =Hash(key);

	if(SearchNot (hash , key , pos))
	{
		hash->hashTable[pos] = _ApplyNode(key , hash->hashTable[pos]);
		if(s == NULL)
		{
			hash->hashTable[pos] = s;
			return 1;
		}
	return 0;
}
//删除
void DeleteHash(MyHash *hash , KeyType key)
{
	if(hash == NULL)  exit(0);

	int pos = Hash(key);

	HashNode *p = hash->hashTable[pos];
	HashNode *pr = NULL;

	while(p != NULL)
	{
		if(p->key == key)
		{
			break;
		}
		pr = p;
		p=p->next;
	}
	if(p == NULL)
      {
	      return 0;
      }
//链表中的第一个节点就是要删的节点,头删法(不带头结点的单链表)
   if(pr == NULL)
     {
	      hash ->hashTable[pos] = p->next;
	      free(p);
     }
   else
    {
	      pr->next = p->next;
	      free(p);
    }
          return 1;
}
//销毁
void DestroyHash(HashNode *hash , KeyType , key)
{
	if(hash == NULL)  exit(0);

	for(int i ; i<HASHNUM ; ++i)
	{
		while(hash->hashTable[i] != NULL)
		{
			HashNode *p = hash->hashTable[i];
			hash->hashTable[i] = p->next;
			free(p);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值