首页 > 代码库 > hash查找
hash查找
#include<stdio.h>#include<stdlib.h>#include<iostream>using namespace std; #define HASHSIZE 7#define NULLKEY -32768 struct HashTable{ int *elem; int count;};void init(HashTable* hashTable){ hashTable->elem = (int*)malloc(HASHSIZE * sizeof(int)); hashTable->count = HASHSIZE; for(int i = 0; i < HASHSIZE; i++) hashTable->elem[i] = NULLKEY; } int hash(int num){ return num % HASHSIZE; } void insert(HashTable* hashTable, int data){ int hash_address = hash(data); while(hashTable->elem[hash_address] != NULLKEY) { hash_address = (++hash_address)% HASHSIZE; } hashTable->elem[hash_address] = data; }int search(HashTable* hashTable, int data){ int hash_address = hash(data); while(hashTable->elem[hash_address] != data) { hash_address = (++hash_address)% HASHSIZE; if(hashTable->elem[hash_address] == NULLKEY || hash_address == hash(data)) return -1; } return hash_address;}void display(HashTable* hashTable) { for(int i = 0; i < hashTable->count; i++) std::cout<<hashTable->elem[i]<<std::endl; }int main(){ HashTable hashTable; int a[HASHSIZE] = {13,29,27,28,26,30,38}; init(&hashTable); for(int i = 0; i< HASHSIZE; i++) { insert(&hashTable, a[i]); } display(&hashTable); int result = search(&hashTable, 29); std::cout<<result<<std::endl; return 0; }
hash查找
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。