• 第11章 散列表


    #include<stdio.h>
    #include<stdlib.h>
    
    unsigned int hashIndex1(const char *key, unsigned int tablesize)
    {
    	unsigned int val = 0;
    	while (*key != '')
    		val += *key++;
    	return val%tablesize;
    }
    unsigned int hashIndex2(const char *key, unsigned int tablesize)
    {
    	return (key[0] + 27 * key[1] + 729 * key[2]) % tablesize;
    }
    unsigned int hashIndex3(const char *key, unsigned int tablesize)
    {
    	unsigned int val = 0;
    	while (*key != '')
    		val = (val << 5) + *key++;
    	return val%tablesize;
    }
    unsigned int hashIndex4(unsigned int key, unsigned int tablesize)
    {
    	return key%tablesize;
    }
    struct ListNode{
    	int value;
    	ListNode* next;
    };
    struct HashTab{
    	int tablesize;
    	ListNode** list;
    };
    HashTab initializeTable(int tablesize)
    {
    	HashTab h;
    	h.tablesize = tablesize;
    	h.list = (ListNode**)malloc(sizeof(ListNode*)*tablesize);
    	for (int i = 0; i < tablesize; ++i)
    		h.list[i] = NULL;
    	return h;
    }
    ListNode* FindHash(HashTab h, int key)
    {
    	ListNode* L = h.list[ hashIndex4(key, h.tablesize) ];
    	while (L&&L->value != key) L = L->next;
    	return L;
    }
    void InsertHash(HashTab h, int key)
    {
    	ListNode* p = FindHash(h, key);
    	if (p == NULL){
    		ListNode* newcell = (ListNode*)malloc(sizeof(ListNode));
    		newcell->next = NULL;
    		newcell->value = key;
    		//printf("%d
    ", hashIndex4(key, h.tablesize));
    		int index = hashIndex4(key, h.tablesize);
    		if (h.list[index] == NULL) h.list[index] = newcell;
    		else{
    			newcell->next = h.list[index];
    			h.list[index] = newcell;
    		}
    	}
    }
    
    void printHash(HashTab h)
    {
    	ListNode* tmp;
    	for (int i = 0; i < h.tablesize; ++i){
    		tmp = h.list[i];
    		while (tmp){
    			printf("%d	", tmp->value);
    			tmp = tmp->next;
    		}
    		printf("
    ");
    	}
    }
    int main()
    {
    	int a[] = { 4, 2, 2, 0, 20, 11, 15, 18, 20, 13 };
    	HashTab h = initializeTable(5);
    	for (int i = 0; i < 10; ++i)
    		InsertHash(h, a[i]);
    	printHash(h);
    }
    

      

  • 相关阅读:
    与非
    抄卡组
    数据结构》关于差分约束的两三事(BZOJ2330)
    刷题向》图论》BZOJ1179 关于tarjan和SPFA的15秒(normal)
    图论算法》关于tarjan算法两三事
    图论算法》关于SPFA和Dijkstra算法的两三事
    刷题向》DP》值得一做》关于对DP问题的充分考虑(normal)
    数据结构》关于线段树两三事(新手向)(工具向)
    图论算法》关于匈牙利算法的两三事
    关于羊和车的问题
  • 原文地址:https://www.cnblogs.com/jokoz/p/4698710.html
Copyright © 2020-2023  润新知