Home Backend Development PHP Tutorial 兑现极小一部分PHP的HASHMAP

兑现极小一部分PHP的HASHMAP

Jun 13, 2016 am 11:03 AM
gt hashtable ht

实现极小一部分PHP的HASHMAP
又修改了一下,实现了resize

#include <stdlib.h>#include <stdio.h>#include <string.h>#include <malloc.h>#include <math.h>typedef struct bucket{	int h;  	char* key;	void* pData;	struct bucket* pNext;	struct bucket* pLast;}Bucket;typedef struct hashtable{	int size;	int elementsNum;	int mask;	Bucket** arBuckets; //这是一个存放buckets的array }HashTable;/** **  这是一个计算HASH值的算法 **/int time33(char* arKey,int arlength){	int h = 0;	int i;	for(i=0;i<arlength;i++){		h = h*33 + (int)*arKey++;	}	return h;	}/** **  初始化一个大小是1的HASHTABLE  **/int _init_hash_table(HashTable** ht){	*ht = (HashTable*)malloc(sizeof(HashTable));	(*ht)->size = 1;	(*ht)->mask = (*ht)->size - 1;	    (*ht)->elementsNum = 1;	(*ht)->arBuckets = (Bucket**)malloc(sizeof(Bucket*)*(*ht)->size);	memset((*ht)->arBuckets,0,sizeof(Bucket*)*(*ht)->size);	return 1;		} int _hash_link_bucket_to_bucket_head(Bucket** newBucket,Bucket** bucketHead){	if(*bucketHead==NULL){		*bucketHead = *newBucket;			}else{		(*newBucket)->pNext = (*bucketHead)->pNext;		(*newBucket)->pLast = (*bucketHead);		if((*bucketHead)->pNext != NULL){			(*bucketHead)->pNext->pLast = *newBucket;			}		(*bucketHead)->pNext = *newBucket;		}	return 1;}int _hash_new_bucket(Bucket** newBucket,int hash,char* arkey,void* pData){	(*newBucket) = (Bucket*)malloc(sizeof(Bucket));	(*newBucket)->h = hash;	(*newBucket)->key = arkey;	(*newBucket)->pData = pData;	(*newBucket)->pNext = NULL;	(*newBucket)->pLast = NULL;	return 1;}int _hash_rehash(HashTable* ht){	int i = 0;	//由于我没定义pListNext指针,所以只能这样rehash了。 	for( ; i<ht->size ; i++){		if(ht->arBuckets[i] != NULL){			int index = ht->arBuckets[i]->h & ht->mask ;			if(i != index){				_hash_link_bucket_to_bucket_head(&ht->arBuckets[i],&ht->arBuckets[index]);				ht->arBuckets[i] = NULL;				}			}		}	return 1;		}/** **  将HASHTABLE的大小扩容1倍  **/int _hash_resize(HashTable* ht){	if(ht != NULL){		ht->size = ht->size << 1;		ht->mask = ht->size - 1; 		realloc(&ht->arBuckets,sizeof(Bucket*) * ht->size);		int i;		for(i=ht->size>>1;i<ht->size;i++){			ht->arBuckets[i] = NULL;		}		//memset(ht->arBuckets[0],NULL,sizeof(Bucket*) * (ht->size >> 1));		printf("resize:%i\r\n", ht->size);		_hash_rehash(ht);		return 1;			}	return 0;}/** **  往HASHTABLE中添加元素  **/int _hash_add_or_update(HashTable* ht,char* arKey,int arLength,void* pData){	int h = time33(arKey,arLength);	int index = h & ht->mask;	Bucket* p = ht->arBuckets[index]; 	while(p!=NULL){		if(strcmp(arKey,p->key)==0){			//这里应该执行更新操作			free(p->pData);			p->pData = pData; 			return 1;		}		p = p->pNext;			}	Bucket* newBucket;	_hash_new_bucket(&newBucket,h,arKey,pData);	_hash_link_bucket_to_bucket_head(&newBucket,&ht->arBuckets[index]);	ht->elementsNum++;	if(ht->elementsNum = ht->size){		_hash_resize(ht);	}	return 0;	}void* _hash_find(HashTable* ht,char* arKey,int arLength){	int h = time33(arKey,arLength);	int index = h & ht->mask;	Bucket* p = ht->arBuckets[index]; 	while(p!=NULL){		if(strcmp(arKey,p->key)==0){			return p->pData;		}		p = p->pNext;	}	return 0;}int PUT(HashTable* ht,void* key,void* value){	char* arKey = (char*)key;	int len = strlen(arKey);	return _hash_add_or_update(ht,arKey,len,value);	}void* GET(HashTable* ht,void* key){	char* arKey = (char*)key;	int len = strlen(arKey);	return _hash_find(ht,arKey,len);}int main(){	printf("%s\r\n","这是一个hashtable的例子");	HashTable* ht;	_init_hash_table(&ht);	PUT(ht,"1","mengjun");	PUT(ht,"2","aaaaa");	PUT(ht,"3","fff");	PUT(ht,"24","eee");	PUT(ht,"25","ddd");	printf("%s\r\n",(char*)GET(ht,"1"));	printf("%s\r\n",(char*)GET(ht,"2"));	printf("%s\r\n",(char*)GET(ht,"3"));	printf("%s\r\n",(char*)GET(ht,"24"));	printf("%s\r\n",(char*)GET(ht,"25"));	printf("HASHTABLE总共有元素%i个\r\n",ht->elementsNum);	return 0;}
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Using the isEmpty() method of the Hashtable class in Java to determine whether the hash table is empty Using the isEmpty() method of the Hashtable class in Java to determine whether the hash table is empty Jul 24, 2023 pm 02:21 PM

In Java, the isEmpty() method of the Hashtable class is used to determine whether the hash table is empty. The hash table is one of the commonly used data structures in the Java collection framework. It implements the storage and retrieval of key-value pairs. In the Hashtable class, the isEmpty() method is used to determine whether the hash table is empty. This article will introduce how to use the isEmpty() method of the Hashtable class and provide corresponding code examples. First, we need to understand the Hashtable class. Hash

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

Is watch4pro better or gt? Is watch4pro better or gt? Sep 26, 2023 pm 02:45 PM

Watch4pro and gt each have different features and applicable scenarios. If you focus on comprehensive functions, high performance and stylish appearance, and are willing to bear a higher price, then Watch 4 Pro may be more suitable. If you don’t have high functional requirements and pay more attention to battery life and reasonable price, then the GT series may be more suitable. The final choice should be decided based on personal needs, budget and preferences. It is recommended to carefully consider your own needs before purchasing and refer to the reviews and comparisons of various products to make a more informed choice.

Use the containsKey() method of the Hashtable class in Java to determine whether the key exists in the hash table Use the containsKey() method of the Hashtable class in Java to determine whether the key exists in the hash table Jul 25, 2023 pm 12:00 PM

In Java, the containsKey() method of the Hashtable class is used to determine whether the key exists in the hash table. In Java programming, the Hashtable class can be used to store and manage data using a hash table. A hash table is a data structure used to store key-value pairs, enabling fast data access by mapping keys to values. In the actual programming process, we often need to determine whether a specific key exists in the hash table. In order to achieve this function, we can use the Hashtable class to provide

What is HT coin? Is HT Coin valuable? What is HT coin? Is HT Coin valuable? Feb 27, 2024 pm 10:49 PM

HT Coin: Huobi platform currency with unlimited potential Introduction HT Coin is the platform currency of Huobi Global and was officially launched on January 16, 2018. The total circulation is 500 million, of which 60% is used for market circulation, and the remaining 40% is allocated to team incentives, ecological construction, repurchase and destruction, etc. Purpose The main uses of HT coins include: Transaction fee reduction: HT coin holders can enjoy transaction fee reduction when trading on Huobi Global. The greater the holding, the higher the reduction ratio. Participate in IEO: HT coin holders have priority to participate in the IEO on Huobi Global. Mortgage lending: HT coins can be mortgaged and borrowed on Huobi Global. Participate in community governance: HT coin holders can participate in the community governance of Huobi Global and make suggestions for the development of the platform.

See all articles