llist.c
contents ::
  app.c
  foo.c
  llist.c
  llist.h
  mylib.c
  mylib.h

#include <stdio.h>
#include <stdlib.h>
#include "llist.h"
#include "mylib.h"

#define FALSE 0
#define TRUE 1
#define null NULL

typedef int boolean;

static list_node *list_node_new(kdpair k, list_node *next){
  list_node *ln = emalloc(sizeof *ln);
  ln->item = k;
  ln->next = next;
  return ln;
}

llist llist_new(){
  llist l = emalloc(sizeof *l);
  l->first = NULL;
  l->last = NULL;
  l->length = 0;
  return l;
}

void llist_insert(llist l, kdpair k){
  list_node *ln = list_node_new(k, l->first);
  if(l->last == NULL){
    l->last = ln;
  }
  l->first = ln;
  l->length++;
}

kdpair *llist_search(llist l, int key){
  list_node *ln = l->first;
  boolean found = TRUE;
  kdpair *kd = emalloc(sizeof *kd);
  while(ln->item.key != key){
    // fprintf(stderr, "node item key: %d\n", ln->item.key);
    if(ln->next == NULL){
      found = FALSE;
      break;
    }
    ln = ln->next;
  }
  if(found){
    kd->key = ln->item.key;
    kd->data = ln->item.data;
    return kd;
  } else
    return NULL;
}

void llist_delete(llist l, int key){
  list_node *target = l->first;
  list_node *prev = null;
  boolean found = TRUE;

  while(target->item.key != key){
    if(target->next == NULL){
      found = FALSE;
      break;
    }
    prev = target;
    target = target->next;
  }
  if(found){
    if(l->first == target)
      l->first = target->next;
    if(l->last == target)
      l->last = prev;
    if(prev != null)
      prev->next = target->next;
    free(target);
    l->length--;
  }
}

void llist_iterate(llist l, void f(kdpair k)){
  list_node *ln = l->first;
  
  while(1){
    f(ln->item);
    // ln->item.key++;
    if(ln->next == NULL)
      break; 
    ln = ln->next;
  }
  
}

void llist_print(llist l){
  list_node *ln = l->first;

  while(1){
    fprintf(stderr, "node item key: %d\n", ln->item.key);
    if(ln->next == NULL)
      break; 
    ln = ln->next;
  }
}

James Little