您当前的位置: 首页 >  c语言
  • 2浏览

    0关注

    880博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

哈希表---C语言实现

CodeAllen嵌入式编程 发布时间:2018-09-03 23:25:31 ,浏览量:2

哈希的基本理解---按照某种函数存储地址

 

冲突问题:

#include

#include

#include

#include

#define SIZE 20

struct DataItem {  //键值

   int data;  

   int key;

};

struct DataItem* hashArray[SIZE];

struct DataItem* dummyItem;

struct DataItem* item;

int hashCode(int key) {

   return key % SIZE; 

}

struct DataItem *search(int key){              

   //get the hash

   int hashIndex = hashCode(key);  //key%SIZE

    

   //move in array until an empty

   while(hashArray[hashIndex] != NULL){

      if(hashArray[hashIndex]->key == key)

         return hashArray[hashIndex];

            

      //go to next cell

      ++hashIndex;

        

      //wrap around the table

      hashIndex %= SIZE;

   }       

   return NULL;       

}

void insert(int key,int data){

   struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));

   item->data = data; 

   item->key = key;    

   //get the hash

   int hashIndex = hashCode(key);

   //move in array until an empty or deleted cell

   while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1){

      //go to next cell

      ++hashIndex;

        

      //wrap around the table

      hashIndex %= SIZE;

   }

   hashArray[hashIndex] = item;       

}

struct DataItem* delete(struct DataItem* item){

   int key = item->key;

   //get the hash

   int hashIndex = hashCode(key);

   //move in array until an empty

   while(hashArray[hashIndex] != NULL){

    

      if(hashArray[hashIndex]->key == key){

         struct DataItem* temp = hashArray[hashIndex];

            

         //assign a dummy item at deleted position

         hashArray[hashIndex] = dummyItem;

         return temp;

      }

        

      //go to next cell

      ++hashIndex;

        

      //wrap around the table

      hashIndex %= SIZE;

   }       

   return NULL;       

}

// 显示所示数据项

void display(){

   int i = 0;

    

   for(i = 0; ikey,hashArray[i]->data);

      else

         printf(" ~~ ");

   }

    

   printf("\n");

}

int main(){

  

   dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem));

   dummyItem->data = -1; 

   dummyItem->key = -1;

   insert(1, 20);

   insert(2, 70);

   insert(42, 80);

   insert(4, 25);

   insert(12, 44);

   insert(14, 32);

   insert(17, 11);

   insert(13, 78);

   insert(37, 97);

   display();

   item = search(37);

   if(item != NULL){

      printf("Element found: %d\n", item->data);

   }else{

      printf("Element not found\n");

   }

   delete(item);

   item = search(37);

   if(item != NULL){

      printf("Element found: %d\n", item->data);

   }else{

      printf("Element not found\n");

   }

}

 

关注
打赏
1665938897
查看更多评论
立即登录/注册

微信扫码登录

0.0426s