Hash Table with Chaining

Learn Theory- Chaining

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define size 10
struct node
{
    int data;
    struct node *next;
};

struct node *chain[size];

void init()
{
    int i;
    for(i = 0; i < size; i++)
        chain[i] = NULL;
}

void insert(int value)
{
    //create a newnode with value
    int key;
    struct node *newNode = malloc(sizeof(struct node));
    newNode->data = value;
    newNode->next = NULL;

    //calculate hash key
    key = value % size;

    //check if chain[key] is empty
    if(chain[key] == NULL)
chain[key] = newNode;
    //collision
    else
    {
//add the node at the end of chain[key].
struct node *temp = chain[key];
while(temp->next)
{
    temp = temp->next;
}

temp->next = newNode;
    }
    printf("Entered Value added to hash table\n");
}

void printhashtable()
{
    int i;

    for(i = 0; i < size; i++)
    {
struct node *temp = chain[i];
printf("chain[%d]-->",i);
while(temp)
{
    printf("%d -->",temp->data);
    temp = temp->next;
}
printf("NULL\n");
    }
}

void main()
{
    //init array of list to NULL
    int i,num,val;
  
    init();
    printf("Enter the number of elements\n");
    scanf("%d",&num);
    for(i=0;i<num;i++)
    {
    printf("Enter Elements\n");
    scanf("%d",&val);
    insert(val);
    }
    printf("\n\n The hash table is\n\n");
    printhashtable();
    getch();

}

Comments

Popular posts from this blog

Data Structure Lab CSL 201 Manual KTU - Dr Binu V P-9847390760

Lab Assignments

Polynomial Addition using Arrays