Thursday, 29 June 2017

Hash Table

#define HASHSIZE 197
 
typedef struct node
{
 int value;
 struct node *next;
}mynode;
 
typedef struct hashtable
{
  mynode *llist;
}HT;
 
HT myHashTable[HASHSIZE];
 
int main()
{
 initialize();
 add(2);
 add(2500);
 add(199);
 

 display_hash();
 getch();
 return(0);
}
 
int initialize()
{
  int i;
  for(i=0;i
 
int add(int value)
{
  int hashkey;
  int i;
  mynode *tempnode1, *tempnode2;

  hashkey=value%HASHSIZE;
  printf("\nHashkey : [%d]\n", hashkey);
  if(myHashTable[hashkey].llist==NULL)
  {
    //This hash bucket is empty, add the first element!
    tempnode1 = malloc(sizeof(mynode));
    tempnode1->value=value;
    tempnode1->next=NULL;
    myHashTable[hashkey].llist=tempnode1;
 }
 else
 {
 //This hash bucket already has some items. Add to it at the end.
 //Check if this element is already there?

 for(tempnode1 = myHashTable[hashkey].llist;
         tempnode1!=NULL; tempnode1=tempnode1->next)
 {
   if(tempnode1->value==value)
   {
       printf("\nThis value [%d] already exists in the Hash!\n", value);
       return(1);
    }
 }
 tempnode2 = malloc(sizeof(mynode));
 tempnode2->value = value;
 tempnode2->next=NULL;
 tempnode1=tempnode2;
 }
 return(1);
}
 
int display_hash()
{
  int i;
  mynode *tempnode;
  for(i=0;i (empty)\n",i);
   }
   else
   {
     printf("\nmyHashTable[%d].llist -> ",i);
     for(tempnode=myHashTable[i].llist;
         tempnode!=NULL;tempnode=tempnode->next)
     {
       printf("[%d] -> ",tempnode->value);
     }
    printf("(end)\n");
  }
 
 }//for
 return(0); 

} 
 
And here is the output 
myHashTable[0].llist -> (empty)
myHashTable[1].llist -> (empty)  
myHashTable[2].llist -> [2] -> [199] -> (end)
..
myHashTable[135].llist -> (empty)
myHashTable[136].llist -> [2500] -> (end) 

No comments:

Post a Comment