 |
|
 |
Home : C/C++
Name : hash Table imlementation. Description : Simple hash table implentation.
Code :#include <stdio.h>
#include <string.h>
#include "malloc.h"
struct node {
char name[25];
int phone;
struct node *nxt;
};
struct node *hash[29];
void inp (char*,int);
void op (char*);
void del (char*);
main () {
char nm[25];int s,choice;
choice=1;
while (choice!=0) {
printf ("\n Enter choice:- \n 1.Enter \n 2.View \n 3.Delete \n 0.Exit \n");
scanf ("%d",&choice);
if (choice==1) { printf("Enter name : ");
scanf ("%s",&nm);
printf("Enter phone no. : ");
scanf ("%d",&s);
inp (nm,s);}
if (choice==2) {printf ("Enter name : ");
scanf ("%s",&nm);
op (nm);}
if (choice==3) {printf("Enter name : ");
scanf ("%s",&nm);
del (nm);}
}
}
void inp (char nm[25],int s) {
struct node *temp,*t;int pos;
pos=(strlen(nm)*nm[1])&29;
t=(struct node *)malloc (sizeof (struct node));
temp=hash[pos];
if (hash[pos]==NULL)
{
hash[pos]=t;
}
else
{ t->nxt=hash[pos];
hash[pos]=t;
}
t->phone=s;
strcpy(t->name,nm);
}
void op (char nm[25]) {
int pos;int found;struct node *temp;
pos=(strlen(nm)*nm[1])&29;
found=1;
temp=hash[pos];
while ((temp!=NULL) && (found!=0)) {
if (strcmp(temp->name,nm)==0)
found=0;
else temp=temp->nxt;
}
if (found==1) printf ("entry not found");
else { printf("\n Name :- %s",temp->name);
printf ("\n Phone no.: %d",temp->phone);
}
}
void del (char nm[25]) {
int pos;int found;struct node *temp,*prev;
pos=(nm[1]*strlen(nm))&29;
found=1;prev=NULL;
temp=hash[pos];
while ((temp!=NULL) && (found!=0)) {
if (strcmp(temp->name,nm)==0)
found=0;
else { prev=temp;
temp=temp->nxt;
}
}
if (found==1) printf ("entry not found");
else { if (prev==NULL) hash[pos]=temp->nxt;
else prev->nxt=temp->nxt;
free(temp);
}
}
|
|
 |