Hash基本操作

weixin_45633346發表於2020-11-07
//結構定義
#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);
		}
	}
}