You are on page 1of 3

/*hashing by seperate chaining*/ #include<stdio.h> #include<stdlib.

h> struct node { int data; struct node *next; }; struct node *create(int x) { struct node *t; t=(struct node *)malloc(sizeof(struct node)); t->data=x; t->next=NULL; return t; } void insert(struct node *ht[10],int x,int ts) { struct node *temp=create(x),*t; int i; i=x%ts; if(ht[i]==NULL) ht[i]=temp; else { t=ht[i]; while(t->next!=NULL) t=t->next; t->next=temp; } } int search(struct node *ht[10],int x,int ts) { int i; struct node *t; i=x%ts; if(ht[i]==NULL) return 0; else { t=ht[i]; while(t!=NULL) { if(t->data==x) break; t=t->next; } if(t==NULL) return 0; else return 1; } } void delete(struct node *ht[10],int x,int ts) { int i=0,t; struct node *temp,*pre; i=x%ts; t=search(ht,x,ts); if(t==0)

printf("element was not found"); else { if(ht[i]->data==x) ht[i]=ht[i]->next; else { temp=ht[i]; while(temp!=NULL) { if(temp->data==x) break; pre=temp; temp=temp->next; } pre->next=temp->next; } } } void display(struct node *ht[10],int ts) { int i; struct node *temp; for(i=0;i<ts;i++) { temp=ht[i]; while(temp!=NULL) { printf("%d\t",temp->data); temp=temp->next; } } } main() { int ch,ts,x,i,y; struct node *ht[10]; printf("enter table size"); scanf("%d",&ts); for(i=0;i<ts;i++) ht[i]=NULL; while(1) { printf("\nMENU\n"); printf("1:insert\n2:search\n3:delete\n4:display\n"); printf("enter your choice"); scanf("%d",&ch); switch(ch) { case 1:printf("enter the element to insert"); scanf("%d",&x); insert(ht,x,ts); display(ht,ts); break; case 2:printf("enter the value to be searched"); scanf("%d",&x); y=search(ht,x,ts); if(y==1) printf("element was found"); else

printf("element does not exist"); break; case 3:printf("enter the element to be deleted"); scanf("%d",&x); delete(ht,x,ts); display(ht,ts); break; case 4:display(ht,ts); break; default:exit(0); } } }

You might also like