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

#include "dlist.h"


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

template<class T> void DList<T>:: add(T* elem)
{
    ++noOfElements;

    if (first != 0)  last->next = elem;
    else 	     first = elem;

    elem->prev = last;
    last = elem;
    elem->next = 0;
}
//-------------------------------------------------------------------------

template<class T> void DList<T>:: insert(T* elem)
{
    ++noOfElements;

    if (first != 0) first->prev = elem;
    else	    last = elem;

    elem->next = first;
    elem->prev = 0;
    first = elem;
}
//-------------------------------------------------------------------------

template<class T> void DList<T>:: substitute(T* elem, T* elem1, T* elem2)
{
    ++noOfElements;

    T  *prevElem = elem->prev, *nextElem = elem->next;
    if (elem == first)  first = elem1;
    if (elem == last )  last  = elem2;

    elem1->next = elem2;
    elem2->prev = elem1;
    elem1->prev = prevElem;
    elem2->next = nextElem;
    if (prevElem != 0) prevElem->next = elem1;
    if (nextElem != 0) nextElem->prev = elem2;
}
//-------------------------------------------------------------------------

template<class T> void DList<T>:: remove(T* elem)	// do NOT delete !
{
    --noOfElements;

    if (elem == first)     
    {
	first = elem->next;
	if (elem->next) (elem->next)->prev = 0;
	else last = 0;
    }
    else if (elem == last) 
    {
	last = elem->prev;
	(elem->prev)->next = 0;
    }
    else 
    {
	(elem->prev)->next = elem->next;
	(elem->next)->prev = elem->prev;
    }
}
//-------------------------------------------------------------------------

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

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

template<class T> int DList<T>:: MemSpace() const
{ 
    return noOfElements*sizeof(T) + 2*sizeof(T*) + sizeof(int); 
}
//-------------------------------------------------------------------------
/*
template<class T>  ostream& operator<< (ostream& os, DList<T>& list)
{
    T* l;
    for (l=list.first; l; l=l->next) 
    os << (*l) << " next: " << l->next <<"\n";
    return os;
}
*/
