-2

when I'm adding to a NULL bucket in a hashTable, my function works very well, but it doesn't when there is already a value in that bucket, and I can't find the problem here !?

void myHashSetAdd(MyHashSet* obj, int key) {
  int bucket=key%10;
  ListNode* test=obj->t[bucket],*a;
  if(!test){    // if bucket is empty ( works well )
    obj->t[bucket]=node(key);
  } else {   // if it's full ( here is the problem ) 
    a=node(key);
    a->next=test;   // assign it as the head of the linked list
    obj->t[bucket]=a;
  }
}

Here is My hashTable fucntions:

typedef struct {
  int val;
  struct ListNode *next;
}ListNode;

typedef struct {
    ListNode *t[10];
} MyHashSet;

ListNode *node(int val){   
  ListNode *temp=malloc(sizeof(ListNode));
  temp->val=val,temp->next=0;
  return temp;
}


MyHashSet* myHashSetCreate() {
    MyHashSet *hashTable=malloc(sizeof(MyHashSet));
    for(int i=0;i<10;i++){hashTable->t[i]=0;} // all buckets to NULL;
    return hashTable;
}
Saad Out03
  • 19
  • 2
  • 4
    Questions seeking debugging help should generally provide a [mre] of the problem, which includes a function `main` and all `#include` directives. This allows other people to easily test your program, by simply using copy&paste. – Andreas Wenzel May 21 '22 at 10:39
  • 2
    Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine at which point your program stops behaving as intended? If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Wenzel May 21 '22 at 10:40
  • 1
    Insertion code looks good to me, how do you determine that it’s failing? – 500 - Internal Server Error May 21 '22 at 11:54

0 Answers0