C Program for open hashing
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
void insert_hash(struct node**,int);
void traverse_hash(struct node*);
void delete_hash(struct node**,int);
void search_hash(struct node*,int);
main()
{
int i,ch,key,pos;
struct node* hash[10]={NULL};
while(1)
{
printf("1-INSERTION\n2-TRAVERSING\n3-DELETION\n4-SEARCHING\n5-EXIT\n");
printf("Enter a choice\n");
scanf("%d",&ch);
switch (ch)
{
case 1:
printf("Enter the key\n");
scanf("%d",&key);
pos=key%10;
insert_hash(&hash[pos],key);
break;
case 2:
for(i=0;i<10;i++)
{
printf("hash[%d]:",i);
traverse_hash(hash[i]);
}
break;
case 3:
printf("Enter key\n");
scanf("%d",&key);
pos=key%10;
delete_hash(&hash[pos],key);
break;
case 4:
printf("Enter key\n");
scanf("%d",&key);
pos=key%10;
search_hash(hash[pos],key);
break;
case 5:
exit(0);
}
}
}
void insert_hash(struct node**start,int key)
{
struct node *temp,*temp1,*prev;
temp=(struct node*) malloc (sizeof(struct node));
if (temp==NULL)
{
printf("Linked list is not created\n");
}
else
{
temp->data=key;
temp->link=NULL;
temp1=*start;
prev=*start;
while( temp1!=NULL && key>temp1->data )
{
prev=temp1;
temp1=temp1->link;
}
if (temp1==prev)
{
temp->link=*start;
*start=temp;
}
else
{
temp->link=temp1;
prev->link=temp;
}
}
}
void traverse_hash(struct node*start)
{
struct node*temp;
if (temp==NULL)
printf("linked list is empty\n");
else
{
temp=start;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->link;
}
printf("NULL\n");
}
}
void delete_hash(struct node **start,int key)
{
struct node *temp,*prev;
if (*start==NULL)
printf("linked list is empty\n");
else
{
temp=*start;
prev=*start;
while (temp!=NULL && key!=(temp->data))
{
prev=temp;
temp=temp->link;
}
if (temp==NULL)
printf("Key is not found \n");
else
{
if (temp==prev)
*start=(*start)->link;
else
{
prev->link=temp->link;
}
free(temp);
}
}
}
void search_hash(struct node*start,int key)
{
struct node *temp;
int flag;
if(temp==NULL)
printf("Linked list is empty\n");
else
{
temp=start;
flag=0;
while(temp!=NULL && flag==0)
{
if (key==temp->data)
flag=1;
temp=temp->link;
}
if (flag==0)
printf("Key is not found\n");
else
printf("Key is found\n");
}
}
Output
No comments:
Post a Comment