/*
 $Id: slist.c,v 1.1 1996/10/10 10:01:22 roitzsch Exp $
 (C)opyright 1996 by Konrad-Zuse-Center, Berlin
 All rights reserved.
 Part of the Kaskade distribution
*/

#include "slist.h"


template<class T> SList<T>:: SList() 
{ 
    noOfElements = 0; 
    first = last = 0; 
}

template<class T> void SList<T>:: add(T* elem)
{
    if (first != 0)  last->next = elem;
    else 		first = elem;
    last = elem;
    elem->next = 0;
    ++noOfElements;
}

template<class T> void SList<T>:: insert(T* elem)
{
    if (first != 0) elem->next = first;
    else
    {
	elem->next = 0;
	last = elem;
    }
    first = elem;
    ++noOfElements;
}

template<class T> int SList<T>:: insertAfter(T* elem, T* target)
{
    T *lp;

    for (lp=first; lp; lp=lp->next)  
    {
	if (lp->equal(target))
	{
	    if (lp->equal(last)) last = elem;
	    elem->next = lp->next;
	    lp->next = elem;
	    ++noOfElements;
	    return 1;
	}
    }
    return 0;
}

template<class T> int SList<T>:: insertBefore (T* elem, T* target)
{
    T *lp, *prev=0;

    for (lp=first; lp; lp=lp->next)  
    {
	if (lp->equal(target)) 
	{
	    if (lp->equal(first))
	    {
		elem->next = first;
		first = elem;
	    }
	    else
	    {
		elem->next = lp;
		prev->next = elem;
	    }
	    return 1;
	}
	++noOfElements;
	prev = lp;
    }
    return 0;
}

template<class T> T* SList<T>:: search(T* target)
{
    T *lp;
    for (lp=first; lp; lp=lp->next)  if (lp->equal(target)) return lp;
    return 0;
}

template<class T> T* SList<T>:: inList(T* elem)
{
    T *lp;
    for (lp=first; lp; lp=lp->next)  if (lp->equal(elem)) return lp;
    return 0;
}

template<class T> void SList<T>:: revert()
{
    T* temp, *prev;

    last = first;
    prev = 0;
    while(first)
    {
	temp = first->next;
	first->next = prev;
	prev = first;
	first = temp;
    }
    first = prev;
}
//-------------------------------------------------------------------------

template<class T> void SList<T>:: deleteAll()
{
    if (first)
    {
	T* elem;
        while (first)
	{
	    elem = first;
	    first = first->next;
	    delete elem;
	}
    }
    noOfElements = 0;
    first = last = 0;
}
//-------------------------------------------------------------------------

template<class T> int SList<T>:: MemSpace() const
{ 
    return noOfElements*sizeof(T) + 2*sizeof(T*) + sizeof(int); 
}
//-------------------------------------------------------------------------

template<class T> void SList<T>:: print()
{
    T* l;
    for (l=first; l; l=l->next) l->print();
}
