Commit 7c9ac109 authored by Lenitra's avatar Lenitra
Browse files

Lists

parent 6fcaad20
Loading
Loading
Loading
Loading
+55 −1
Changes for src/list.c: 55 added lines, 1 removed line.
Original line number Diff line number Diff line


struct cell_t {
  void* val;
  unsigned long int id;
@@ -7,30 +9,82 @@ struct cell_t {
typedef struct cell_t* list_t;

list_t list_empty(){
  return NULL;
}

int list_is_empty(list_t l){
  return l == NULL;
}

list_t list_push(list_t l, void* x){
  // add x to the end of l
  struct cell_t* c = malloc(sizeof(struct cell_t));
  c->val = x;
  c->id = 0;
  c->next = NULL;
  if(l == NULL){
    return c;
  }
  struct cell_t* cur = l;
  while(cur->next != NULL){
    cur = cur->next;
  }
  cur->next = c;
  return l;
}

list_t list_tail(list_t l){
  if(list_is_empty(l)){
    return NULL;
  }
  // Get all the list whithout the first element
  list_t l_tail = l->next;
  free(l);
  return l_tail;
}

void* list_pop(list_t* l){ 
  // remove the first element of l and return it
  if(list_is_empty(*l)){
    return NULL;
  }
  struct cell_t* c = *l;
  *l = c->next;
  void* val = c->val;
  free(c);
  return val;
}

void* list_top(list_t l){
  if(list_is_empty(l)){
    return NULL;
  }
  return l->val;
}

void list_destroy(list_t l, void (*free)(void*)){
  // free all the memory allocated by l
  while(!list_is_empty(l)){
    free(list_pop(&l));
  }
}

// return the found element or NULL
void* list_in(list_t l, void* x, int (*eq)(void*, void*)){
  while(!list_is_empty(l)){
    if(eq(x, l->val)){
      return l->val;
    }
    l = l->next;
  }
  return NULL;
}

unsigned long int list_len(list_t l){
  unsigned long int len = 0;
  while(!list_is_empty(l)){
    len++;
    l = l->next;
  }
  return len;
}
+1 −5
Changes for src/list.h: 1 added line, 5 removed lines.
Original line number Diff line number Diff line
#ifndef __LIST__
#define __LIST__

struct cell_t {
  void* val;
  unsigned long int id;
  struct cell_t* next;
};


typedef struct cell_t* list_t;

File moved.