main.cpp
#include"Hash_List.h"
void main()
{
int i;
ElementType array[10] = {10,7,5,6,9,3,2,4,8,1};
HashList hl;
hl = (HashList)malloc(sizeof (struct HashNode) );
CreatHashList(hl, 10);
for ( i = 0; i < 10; i++)
{
if (Insert(hl,array[i]))
{
printf("%d插入成功\n", array[i]);
}
else
{
printf("%d插入失败\n", array[i]);
}
}
if (Find(hl, 3))
{
printf("元素3在哈希链表中\n");
}
else
{
printf("元素3不在哈希链表中\n");
}
if (Find(hl, 2333))
{
printf("元素2333在哈希链表中\n");
}
else
{
printf("元素2333不在哈希链表中\n");
}
}
HashList.h
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef int Position;
typedef struct LNode {
ElementType data;
struct LNode* Next;
}*List;
typedef struct HashNode {
int ArrayTableSize;
List list;
}*HashList;
void CreatHashList(HashList hl, int length);
bool Find(HashList hl, ElementType key);
bool Insert(HashList hl, ElementType key);
#pragma once
HashList.cpp (插入,查找)
#include"Hash_List.h"
Position Hash(HashList hl, int key)
{
return key % hl->ArrayTableSize;
}
void CreatHashList(HashList hl, int length)
{
List l;
l = (List)malloc(sizeof(struct LNode));
hl->ArrayTableSize = length;
hl->list = (List)malloc(sizeof(struct LNode) * length);
for (int i = 0; i < length; i++)
{
l->data = 0;
l->Next = NULL;
hl->list[i] = *l;
}
}
bool Find(HashList hl, ElementType key)
{
List p;
int pos;
pos = Hash(hl,key);
p = &(hl->list[pos]);
while (p->Next && p->data != key)
{
p = p->Next;
}
if (p->data == key)
{
return true;
}
else
{
return false;
}
}
bool Insert(HashList hl, ElementType key)
{
int pos;
List p,s;
s = (List)malloc(sizeof(struct LNode));
if (Find(hl,key))
{
return false;
}
else
{
pos = Hash(hl,key);
p = &(hl->list[pos]);
while (p->Next)
{
p = p->Next;
}
s->data = key;
s->Next = NULL;
p->Next = s;
}
}