#include <types.h>
#include <kern/errno.h>
#include <lib.h>
#include <list.h>

typedef struct list list;
typedef struct node node;
list * newlist(void)
{
  list * ret = kmalloc(sizeof(list));
  if (!(ret)) return NULL;
  ret->front = NULL;
  ret->len = 0;
  return ret;
}

int listsert(list * l, int x)
{
  node * temp = l->front;
  node * newnode = kmalloc(sizeof(node));
  if (!(newnode)) return ENOMEM;
  newnode->val = x;
  newnode->next = temp;
  l->front = newnode;
  ++l->len;
  return 0;
}

void listemove(list * l, int x)
{
  node * temp = l->front;
  node * temp2 = NULL;
  
  while (temp)
  {
    if (temp->val == x)
    {
      if (!(temp2))
      {
        l->front = temp->next;
      }
      else
      {
        temp2->next = temp->next;
      }
      
      --l->len;
      break;
    }
    else
    {
      temp2 = temp;
      temp = temp->next;
    }
  }
}

void listelete(list * l)
{
  node * temp = l->front;
  node * temp2 = NULL;
  
  while (temp)
  {
    temp2 = temp->next;
    kfree(temp);
    temp = temp2;
  }
  
  kfree(l);
}

int listearch(list * l, int x)
{
  node * temp = l->front;

  while (temp)
  {
    if (temp->val == x) return 1;
    temp = temp->next;
  }
  
  return 0;
}

int listpop(list * l)
{
  node * temp = l->front;
  
  if (temp)
  {
    int x = temp->val;
    l->front = temp->next;
    --l->len;
    kfree(temp);
    return x;
  }
  
  return 0;
}
