hash table with chaining method program freezing

Posted by Justin Carrey on Stack Overflow See other posts from Stack Overflow or by Justin Carrey
Published on 2012-10-31T16:54:47Z Indexed on 2012/10/31 17:00 UTC
Read the original article Hit count: 117

Filed under:
|
|
|
|

I am implementing hash table in C using linked list chaining method. The program compiles but when inserting a string in hash table, the program freezes and gets stuck. The program is below:

struct llist{
    char *s;
    struct llist *next;
};

struct llist *a[100];

void hinsert(char *str){
    int strint, hashinp;
    strint = 0;
    hashinp = 0;
    while(*str){
            strint = strint+(*str);
    }
    hashinp = (strint%100);
    if(a[hashinp] == NULL){
            struct llist *node;
            node = (struct llist *)malloc(sizeof(struct llist));
            node->s = str;
            node->next = NULL;
            a[hashinp] = node;
    }
    else{
            struct llist *node, *ptr;
            node = (struct llist *)malloc(sizeof(struct llist));
            node->s = str;
            node->next = NULL;
            ptr = a[hashinp];
            while(ptr->next != NULL){
                    ptr = ptr->next;
            }
            ptr->next = node;
    }
}  

void hsearch(char *strsrch){
    int strint1, hashinp1;
    strint1 = 0;
    hashinp1 = 0;
    while(*strsrch){
            strint1 = strint1+(*strsrch);
    }
    hashinp1 = (strint1%100);
    struct llist *ptr1;
    ptr1 = a[hashinp1];
    while(ptr1 != NULL){
            if(ptr1->s == strsrch){
                    cout << "Element Found\n";
                    break;
            }
            else{
                    ptr1 = ptr1->next;
            }
    }
    if(ptr1 == NULL){
            cout << "Element Not Found\n";
    }
}  

hinsert() is to insert elements into hash and hsearch is to search an element in the hash. Hash function is written inside hinsert() itself. In the main(), what i am initializing all the elements in a[] to be NULL like this:

for(int i = 0;i < 100; i++){
            a[i] = NULL;
    }  

Help is very much appreciated. Thanks !

© Stack Overflow or respective owner

Related posts about c

    Related posts about data-structures