2

Detecting a cycle in Hashtable. Consider you are given a set of key value pairs and these are stored in Hashtable. It is possible that a value can also be a key. If all this key value pairs are stored in Hashtable and given a key we should be able to detect appropriate value for a key. Value will be the entry point of cycle. Example:(Key value pairs)

A->B
B->c
c->D
D->E
E->c

So when asked for value corresponding to key A should return C, value for D should return D.

I did it in following way, but I think there can be a better solution:

int count = 0;
char *keys[50];
getValue(char *key, bool for_cycle){
save_keys_cycle[count] = key;
if(for_cycle){  
    int i=0;

    for(i = 0; i<count;i++ ){
        if(strcmp(key, save_keys_cycle[i])==0){                             
            count = 0;
            return key;         
        }       
    }       

}
count++;
char *value = lookup(hashtable, key);
if(value != null){
    char *value = lookup(hashtable, value);
    if(value != null){
        getValue(value, true);
    }
}else{
    count = 0;
    return value;
}

}

To extract a value the call will be

char *value = getValue(key, false);  // I am using a global hashtable.

This works fine but I want to use dynamic size for char[] and not just 50. It would be appreciable if I can get a better way of doing it.

ashy143
  • 169
  • 11

0 Answers0