#include "CList.h"

CList::CList (void)
{
  rewinded_current = current = head = new element_type;
  head->next = NULL;
}

CList::~CList (void)
{
  delall ();
  delete head;
}

bool
CList::add (void *e)
{
  struct element_type *etmp = new element_type;
  if (etmp == NULL)
    return 0;
  etmp->e = e;
  etmp->next = head->next;
  head->next = etmp;
  return 1;
}

bool
CList::del (void *e)
{
  struct element_type *etmp = head, *enext;
  while (etmp->next != NULL)
    {
      if (etmp->next->e == e)
        {
          enext = etmp->next->next;
          delete (etmp->next);
          if (current == etmp->next)
            current = etmp;
          etmp->next = enext;
          return 1;
        }
      etmp = etmp->next;
    }
  return 0;
}

void
CList::delall (void)
{
  struct element_type *etmp = head->next, *enext;
  while (etmp != NULL)
    {
      enext = etmp->next;
      delete (etmp);
      etmp = enext;
    }
  head->next = NULL;
}

void
CList::rewind (void)
{
  rewinded_current = current;
  current = head;
}

void *
CList::next (void)
{
  if (current->next == NULL)
    return NULL;
  current = current->next;
  return current->e;
}

size_t
CList::count (void)
{
  size_t num = 0;
  struct element_type *etmp = head->next;
  while (etmp != NULL)
    {
      num++;
      etmp = etmp->next;
    }
  return num;
}

void
CList::restore_current (void)
{
  current = rewinded_current;
}

bool
CList::exist (void *e)
{
  struct element_type *etmp = head->next;
  while (etmp != NULL)
    {
      if (etmp->e == e)
        return 1;
      etmp = etmp->next;
    }
  return 0;
}
