Commit d88cbd8d authored by Lenitra's avatar Lenitra
Browse files

hash

parent 2bf30818
Loading
Loading
Loading
Loading
+63
Changes for src/bst.c: 63 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -15,19 +15,82 @@ typedef struct bst_t {
} bst_t;

bst_t bst_empty(void){
  bst_t bst;
  bst.h = NULL;
  bst.size = 0;
  bst.tree = NULL;
  return bst;
}

int bst_is_empty(bst_t t){
  return t.tree == NULL;
}

bst_t bst_add(bst_t t, void* x){
  if (t.h == NULL)
    return t;

  unsigned long int key = t.h(x);
  struct node_t* node = malloc(sizeof(*node));
  node->key = key;
  node->val = x;
  node->left = NULL;
  node->right = NULL;

  if (bst_is_empty(t)){
    t.tree = node;
    t.size = 1;
    return t;
  }

  struct node_t* current = t.tree;
  while (current != NULL){
    if (key < current->key){
      if (current->left == NULL){
        current->left = node;
        t.size++;
        return t;
      }
      current = current->left;
    }
    else if (key > current->key){
      if (current->right == NULL){
        current->right = node;
        t.size++;
        return t;
      }
      current = current->right;
    }
    else{
      // key == current->key

  }
}

void bst_destroy(bst_t t, void (*free_void)(void*)){
}

int bst_in(bst_t t, void* x){
  if (t.h == NULL)
    return 0;

  unsigned long int key = t.h(x);
  struct node_t* current = t.tree;
  while (current != NULL){
    if (key < current->key){
      current = current->left;
    }
    else if (key > current->key){
      current = current->right;
    }
    else{
      // key == current->key
      return 1;
    }
  }
  return 0;
}

unsigned long int bst_size(bst_t t){
  return t.size;
}
+28
Changes for src/hash_tbl.c: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -17,14 +17,42 @@ typedef struct hash_tbl* hash_tbl;
hash_tbl htbl_empty(size_t (*h)(void*),
                    int (*eq)(void*, void*),
                    void (*free)(void*)){
  hash_tbl t = malloc(sizeof(*t));
}

int htbl_add(hash_tbl htbl, void* x){
  size_t key = htbl->h(x);
  size_t index = key % htbl->capacity;
  list_t l = htbl->array[index];
  if (l == NULL){
    l = list_empty();
    htbl->array[index] = l;
  }
  l = list_push(l, x);
  htbl->size++;
}

int htbl_in(hash_tbl htbl, void* x){
  size_t key = htbl->h(x);
  size_t index = key % htbl->capacity;
  list_t l = htbl->array[index];
  if (l == NULL)
    return 0;
  return list_in(l, x, htbl->eq);
}

void htbl_destroy(hash_tbl htbl){
  for (size_t i = 0; i < htbl->capacity; i++){
    list_t l = htbl->array[i];
    while (l != NULL){
      list_t tmp = l;
      l = l->next;
      if (htbl->free != NULL)
        htbl->free(tmp->val);
      free(tmp);
    }
  }
  free(htbl->array);
  free(htbl);
}