C++链表的简单创建,用哈希存储,拉链法解决冲突(输出清晰版),(基础认知请回到基础版学习)

#include <stdio.h>

#include <malloc.h>

typedef struct Node

{

int key;

int value;

struct Node *next;

}HashNode;

typedef struct Table

{

HashNode **Array_pointer;

int size;

}HashTable;

void create_table(HashTable *table,int size)

{

table->size = size;

table->Array_pointer = (HashNode**)malloc(size * sizeof(HashNode*));

for (int i = 0;i < size; i++)

{

table->Array_pointer[i] = NULL;

}

}

int add_data(HashTable *table,int key,int value)

{

HashNode *head = (HashNode*)malloc(sizeof(HashNode));

head->key = key;

head->value = value;

head->next = NULL;

HashNode *z_head = NULL;

int index = key % table->size;

if(table->Array_pointer[index] == NULL)

{

table->Array_pointer[index] = head;

}

else

{

z_head = table->Array_pointer[index];

while(z_head->next != NULL)

{

z_head = z_head->next;

}

z_head->next = head;

}

return 1;

}

int get_data(HashTable *table,int key)

{

HashNode *head = NULL;

int index = key % table->size;

head = table->Array_pointer[index];

while(head != NULL && head->key != key)

{

head = head->next;

}

if(head == NULL)

{

return -1;

}

return head->value;

}

int main()

{

HashTable table;

printf("请输入数组元素个数:\n");

int count;

scanf("%d",&count);

create_table(&table,count); //指针指的都是地址&table表示table的地址

printf("下面开始储存数据:\n");

printf("存入的数据个数必须小于数组元素个数\n");

printf("num <= %d\n",count);

printf("请输入您要储存多少个数据:\n");

int num;

scanf("%d",&num);

for(int i = 0;i < num ; i++) //循环存入数据

{

printf("请输入key值:\n");

int key;

scanf("%d",&key);

printf("请输入value值:\n");

int value;

scanf("%d",&value);

add_data(&table,key,value);

}

int counts;

printf("请输入您要取出多少个数据:\n");

scanf("%d",&counts);

for(int k = 0;k < counts;k++) //循环读出数据

{

int keys;

printf("请输入要取出的数据的key值:\n");

scanf("%d",&keys);

printf("\n");

printf("您要取出的第%d个的数据key为%d,其value为%d\n",k+1,keys,get_data(&table,keys));

}

return 0;

}

点个赞就当鼓励一下博主吧 (●'◡'●)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值