哈希表拉链后的结果就是下图这样
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
typedef struct Node
{
//bool IsHead = 0;
int data = -1;
struct Node *next = NULL;
}SLIST;
int SList_Print(Node *pHead)
{
Node *tmp;
if (pHead == NULL)
{
return -1;
}
while (pHead->next != NULL)
{
printf("%d \t -> \t", pHead->data);
pHead = pHead->next;
}
printf("%d \t", pHead->data);
printf("\n");
return 0;
}
int hash(int bucket,int n)
{
return n % bucket;
}
SLIST* CreateNode(int data)
{
SLIST *pNew;
pNew = (SLIST*)malloc(sizeof(SLIST));
if (pNew == NULL)
{
return NULL;
}
pNew->next = NULL;
pNew->data = data;
return pNew;
}
//找到尾节点
Node* FindEnd(Node *pHead)
{
Node *pEND;
pEND = pHead->next;
while (pEND->next != NULL)
{
pEND = pEND->next;
}
return pEND;
}
int main()
{
//9个hash桶
const int BUCKET = 9;
Node ListNode[BUCKET];
//原始数据如下
int num[] = {1,22,33,47,53,667,78,84,99,103,118,126,13,144,155,166,174,183,197,202};
int ArrSize = sizeof(num) / 4;
//计算每个元素的hash值
int NumHash = -1;
Node *pTail = NULL;
//将每个元素插入到链表中
printf("各元素的hash值为: \n");
for ( int i=0; i < ArrSize ;i++)
{
NumHash = hash(BUCKET, num[i]);
printf("%d -> %d \n", num[i], NumHash);
//创建节点
SLIST *pNode = CreateNode(num[i]);
//判断当前节点是否为第一个节点,如果是第一个节点 则直接插入,如果不是第一个节点 则插入到尾部
//节点创建时 IsHead默认值为非头节点
if (ListNode[NumHash].next == NULL )
{
ListNode[NumHash].next = pNode;
}
else
{
pTail = FindEnd(&ListNode[NumHash]);
//尾插法
pTail->next = pNode;
}
}
//打印hash链表
printf("Hash链表如下所示: \n");
for (int i = 0; i < BUCKET;i++)
{
printf("ListNode[%d]: ",i);
SList_Print(&ListNode[i]);
}
system("pause");
return 0;
}