哈希表数据结构程序代码

本文提供了一个简单的哈希表实现,包括创建哈希表、插入元素以及查找元素的功能。哈希表使用链表解决冲突,插入操作会按照键值有序地将节点添加到对应槽位的链表中,查找操作则遍历链表直到找到目标元素或确认其不存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifndef _HASH_
#define _HASH_

#define N 15
typedef int datatype;

typedef struct node{
    datatype key;
    datatype value;
    struct node *next;
    
}listnode,*linklist;

typedef struct {
    listnode data[N];
}hash;

hash * hash_create();
int hash_insert(hash *HT,datatype key);
linklist hash_search(hash * HT,datatype key);

#endif


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"

hash * hash_create(){//哈希表创建
    hash *ht;
    ht=(hash *)malloc(sizeof(hash));
    if(ht==NULL)
        return NULL;
    memset(ht,0,sizeof(hash));
    return ht;
}

int hash_insert(hash *HT,datatype key){
    if(HT==NULL) return -1;
    linklist p,q;
    p=(linklist)malloc(sizeof(listnode));
    if(p==NULL){
        printf("malloc failed\r\n");
        return -1;
    }
    p->key=key;
    p->value=key%N;
    p->next=NULL;

    //找到插入位置
    q=&(HT->data[p->value]);
	//在哪个数据后面插入
    while(q->next&&q->next->key < p->key){
        q=q->next;
    }
	//插入
    p->next=q->next;
    q->next=p;
    return 0;
}

linklist hash_search(hash * HT,datatype key){//查找
    if(HT==NULL) return NULL;
    linklist p;
    p=&(HT->data[key%N]);
    
    while(p->next&&p->next->key!=key){
        p=p->next;
    }
    if(p->next==NULL){
        printf("not found1\r\n");
        return NULL;
    }else{
        printf("found2\r\n");
        return p;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值