Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

hashtable in C I have implemented the \"ht put\" function to add keys and values

ID: 3787212 • Letter: H

Question

hashtable in C

I have implemented the "ht put" function to add keys and values. But it does not work when it is updating the existing key values.

I want to add an element to the hash table and if the hash table has a key, update the current value that pairs with the key.

-------------------------------------------------------------------

void ht_put(hashtable_t *ht, char *key, void *val) {

unsigned int idx = hash(key) % ht->size;

bucket_t *b = malloc(sizeof(bucket_t));

  

while(b != NULL){

if(b->key == key){

b->val = val;

}

b = b->next;

}

  

b->key = key;

b->val = val;

b->next = ht->buckets[idx];

ht->buckets[idx] = b;

  

  

}

Explanation / Answer

// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"

#define SIZE 5
struct DataItem {
   int data;   
   int key;
} hash[SIZE];
void Insert(int key,int value,int index)
{
   hash[index].key=key;
   hash[index].data=value;
}
void Search(int key,int value,int index)
{
   int flag=0;
   for (int i = 0; i < SIZE; i++)
   {
       if(hash[i].key==key)
       {
           hash[i].data=value;
           flag=1;
       }
   }
   if(flag==0)
   {
       Insert(key,value,index);
   }
}
void display()
{
   int i=0;
   while (hash[i].key!=NULL)
   {
       printf("{%d,%d} ",hash[i].key,hash[i].data);
       i++;
   }

}

int _tmain(int argc, _TCHAR* argv[])
{
   int key,value,i;
   for (i = 0; i <SIZE; i++)
   {
       printf("Enter Key");
       scanf_s("%d",&key);
       printf("Enter value");
       scanf_s("%d",&value);
       Insert(key,value,i);
       //Search(key,value,i);
   }
   display();
   printf("Enter Key To Insert");
   scanf_s("%d",&key);
   printf("Enter value To Insert");
   scanf_s("%d",&value);
   Search(key,value,i);
   display();

   return 0;
}