建立簡單的Hash table(哈希表)by C language


 

 1 #define SIZE 1000    //定義Hash table的初始大小
 2 struct HashArray
 3 {
 4     int key;
 5     int count;
 6     struct HashArray* next;
 7 }Hash[SIZE];       //主函數中需要初始化
 8 void addHash(int num)     //在Hash table中添加數據
 9 {
10     int temp=abs(num%SIZE);     //添加的數據可包括負數
11     if(Hash[temp].key==0)
12     {
13         Hash[temp].key=num;
14         Hash[temp].count++;
15     }else if(Hash[temp].key==num)
16     {
17         Hash[temp].count++;     
18     }else
19     {
20         struct HashArray *p=&Hash[temp]; 
21         while(p->key!=num&&p->next!=NULL)    
22         {p=p->next;}
23         if(p->key==num)
24         {p->count++;}
25         else
26         {
27             p->next=(struct HashArray*)malloc(sizeof(struct HashArray));
28             p=p->next;
29             p->key=num;
30             p->count=1;
31             p->next=NULL;
32         }
33     }   
34 } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM