Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Node{
- int data;
- struct Node *next;
- };
- int hash_(int key)
- {
- return key%10;
- }
- void myinsert(struct Node **H,int ele){
- struct Node *p = *H;
- struct Node *t = new Node;
- t->data = ele;
- t->next = NULL;
- if(*H==NULL){ // Important to compare index address(*H) rather than p with NULL
- *H=t;
- }else{
- while(p->next!=NULL){
- p=p->next;
- }
- p->next = t;
- }
- }
- void insert(struct Node *HT[], int ele){
- int index=hash_(ele);
- myinsert(&HT[index],ele);
- }
- void print_at_index(struct Node *HT[],int index){
- struct Node *p= HT[index];
- if(p==NULL){
- cout << "No elements here!";
- return;
- }
- while(p!=NULL){
- cout << p->data << " ";
- p=p->next;
- }
- cout << endl;
- }
- void print_all(struct Node *HT[]){
- for(int i=0;i<10;i++){
- struct Node *p= HT[i];
- if(p==NULL){
- cout << i << " -> NULL" << endl;
- }else{
- cout << i << " -> ";
- while(p!=NULL){
- cout << p->data << " -> ";
- p=p->next;
- }
- cout << "NULL";
- cout << endl;
- }
- }
- }
- void del(struct Node * HT[],int key){
- int index = hash_(key);
- struct Node *p = HT[index], *q=NULL;
- if(p->next==NULL){ // Only one node is present
- HT[index] = NULL;
- delete p;
- }else if(key == p->data && p->next!=NULL){ // If first node has the key
- HT[index] = p->next;
- delete p;
- }else{
- while(p->data != key){ // Search for key, else return not found
- q=p;
- p=p->next;
- if(p==NULL and q->data!=key){
- cout << key << " not found!" << endl;
- return;
- }
- }
- q->next = p->next;
- delete p;
- }
- }
- int main(){
- struct Node *HT[10];
- for(int i=0;i<10;i++){
- HT[i]=NULL;
- }
- insert(HT,12);
- insert(HT,22);
- print_at_index(HT,2); // To print all keys at a particular index
- cout << endl;
- //print_all(HT); // To print all the indices in the form of a table
- del(HT,12); // Delete key-12
- print_all(HT);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement