Program to generate a hash table.

#include <iostream>
using namespace std;

struct node {
int key;
node* next;
node() {
next=NULL;
}

};

typedef node* NODE;

int main() {
NODE hashtable[10];
//hashtable with 10 buckets
for(int i=0;i<10;i++) {
//initialize buckets to NULL
hashtable[i]=NULL;
}
int key;
while(1) {
cout<<"Enter key/bucket(only positive) (-1 to stop):";
cin>>key;

if(key==-1)
break;
NODE temp=new node;
temp->key=key;
//hashfunction:using the remainder hash function to find bucket
int bucket=key%10;
NODE head=hashtable[bucket];

temp->next=head;
hashtable[bucket]=temp;
}
while(1) {
cout<<"Enter key to search(-1 to stop):";
cin>>key;
if(key==-1)
break;
int bucket=key%10;
NODE head=hashtable[bucket];
bool found=false;
while(head!=NULL) {
if(head->key==key) {
found=true;
break;
}
head=head->next;
}
if(found)
cout<<"Key found, Bucket:"<<bucket<<endl;
else
cout<<"Not found"<<endl;
}
return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s