zoukankan      html  css  js  c++  java
  • 第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);
    }
    

      

  • 相关阅读:
    django 添加字段, migrate时候生成一个默认值
    django 开发经验
    GeoIP2-python
    一些好用的django模块
    ubuntu linux samba
    动画工作室
    以太坊dApp全栈开发教程(引言)
    社交网络去中心化已成趋势,读懂核心底层技术选择和路线
    CryptoCurrency Security Standard (CCSS)
    HARNESS THE POWER OF DISTRIBUTED STORAGE IPFS AND SWARM IN ETHEREUM BLOCKCHAIN APPLICATIONS
  • 原文地址:https://www.cnblogs.com/jokoz/p/4698710.html
Copyright © 2011-2022 走看看