#include<stdio.h> //链表 typedef struct listNode { int val; listNode *next; listNode(int key):val(key),next(NULL){} listNode():val(0),next(NULL){} }*position; typedef position list; //散列表 typedef struct hashTbl { int tableSize; list *theLists; }*hashTable; int hash(int key,int tableSize) { return key%tableSize; } //散列表初始化 hashTable init(int tableSize) { //局部 hashTable H; int i; //分配表 H=new hashTbl(); H->tableSize=tableSize; //分配链表数组 H->theLists=new list[H->tableSize]; //分配链表头 for(int i=0;i<H->tableSize;i++) { H->theLists[i]=new listNode(); H->theLists[i]->next=NULL; } return H; } position find(int key,hashTable H) { position p; list l; l=H->theLists[hash(key,H->tableSize)]; p=l->next; while(p!=NULL && p->val!=key) p=p->next; return p; } //插入 void insert(int key,hashTable H) { //局部 position pos,newCell; list l; //是否已存 pos=find(key,H); //未存 if(pos==NULL) { newCell=new listNode(key); l=H->theLists[hash(key,H->tableSize)]; newCell->next=l->next; l->next=newCell; } } int main() { hashTable H=init(5); insert(1,H); insert(2,H); insert(3,H); insert(6,H); return 0; }
原文地址:http://blog.csdn.net/u013011841/article/details/42122293