C Program For Hasing

#include<stdio.h>
#include<conio.h>
#define tsize 21
struct list
  {
    int data;
    struct list *next;
  };
struct htable
  {
    int noofele;
    struct list *head;
  };
main()
  {
    struct htable h[tsize];
    int key;
    char ch;
    init(&h);
    clrscr();
    do{
 printf("\n Enter the Key to insert: ");
 scanf("%d",&key);
 insert(key,&h);
 printf("\n Do you Want to Continue :");
 ch=getch();
      }while(ch!='n');
    display(&h);
    printf("\n Enter the Key to Delete: ");
    scanf("%d",&key);
    del(key,&h);
    display(&h);
  }
init(struct htable *ht)
  {
    int i;
    for(i=0;i<tsize;i++)
      {
 (ht+i)->noofele=0;
 (ht+i)->head=NULL;
      }
  }
del(int key,struct htable *ht)
  {
    int i;
    struct list *temp,*ptr;
    int index=key%tsize;
    if((ht+index)->noofele==0)
      {
 printf("\n The Element Not Found");
      }
    else
      {
 temp=(ht+index)->head;
 ptr=NULL;
 for(i=0;i<(ht+index)->noofele;i++)
   {
     if(temp->data==key)
       {
  (ht+index)->noofele=(ht+index)->noofele-1;
  if(ptr==NULL)
    {
      (ht+index)->head=temp->next;
      return;
    }
  else
    {
      ptr->next=temp->next;
      return;
    }
       }
      ptr=temp;
      temp=temp->next;
   }
 printf("\n The Element is Not Found");
      }
  }
insert(int key,struct htable *ht)
  {
    int index=key%tsize;
    struct list *newnode = malloc(sizeof(struct list));
    if((ht+index)->noofele==0)
      {
 (ht+index)->noofele=1;
 (ht+index)->head=newnode;
 newnode->data=key;
 newnode->next=NULL;
      }
    else
      {
 (ht+index)->noofele=(ht+index)->noofele+1;
 newnode->next=(ht+index)->head;
 newnode->data=key;
 (ht+index)->head=newnode;
      }
  }
display(struct htable *ht)
  {
    int i,j;
    struct list *temp;
    for(i=0;i<tsize;i++)
      {
 printf("\n Index %d :",i);
 if((ht+i)->noofele>0)
  {
    temp=(ht+i)->head;
    for(j=0;j<(ht+i)->noofele;j++)
     {
       printf("---> %d ",temp->data);
       temp=temp->next;
     }
  }
      }
  }
Bhanu Namikaze

Bhanu Namikaze is an Ethical Hacker, Security Analyst, Blogger, Web Developer and a Mechanical Engineer. He Enjoys writing articles, Blogging, Debugging Errors and Capture the Flags. Enjoy Learning; There is Nothing Like Absolute Defeat - Try and try until you Succeed.

No comments:

Post a Comment