双向循环链表类

/*
双向循环链表(与单链表没有太大的区别)
*/
#include <iostream>
#include <cstdio>
using namespace std;

template <class T> class DlList;
template <class T>
class DlNode    //节点类
{
    private:
        DlNode<T> *prior,*next;
        T data;
        friend class DlList<T>;
    public:
        DlNode( DlNode<T> *pr=NULL,int d=0,DlNode<T> *ne=NULL ):prior(pr),data(d),next(ne) {}
        void setprior( DlNode<T> *a ) { prior=a; }
        void setnext( DlNode<T> *a ) { next=a; }
        void setdata( int d ) { data=d; }
        T *getprior() { return prior; }
        T *getnext() { return next; }
        int getdata() { return data; }
};

template <class T>
class DlList
{
    private:
        DlNode<T> *head;
        int size;
    public:
        DlList( T a[],int n )
        {
            int i;
            DlNode<T> *p;
            head=new DlNode<T>;
            head->prior=head;    head->next=head;
            for( i=n-1;i>=0;i-- )
            {
                p=new DlNode<T>( head,a[i],head->next );
                head->setnext( p );
                head->setprior( p );
            }
            size=n;
        }
        DlNode<T> *index( int loc ); //定位
        bool del( int loc );    //删除
        bool inst( int loc,T el );  //插入
        void print();   //输出
};

template <class T>
DlNode<T> *DlList<T>::index( int loc )
{
    int i;
    DlNode<T> *p;
    if( loc==0 )   return head; //loc为0返回head注意
    if( loc<1 || loc>size ) return NULL;
    i=1;    p=head->next;
    while( i<loc )
    {
        p=p->next;
        i++;
    }
    return p;
}

template <class T>
bool DlList<T>::del( int loc )
{
    DlNode<T> *p;
    if( loc<1 || loc>size ) return false;
    p=index(loc);
    p->prior->setnext( p->next );
    p->next->setprior( p->prior );
    size--;
    return true;
}

template <class T>
bool DlList<T>::inst( int loc,T el )
{
    DlNode<T> *p,*q;
    if( loc<1 || loc>size+1 ) return false;
    p=index(loc-1);
    q=new DlNode<T>( p,el,p->next );
    p->setnext(q);  p->next->setprior(q);
    size++;
    return true;
}

template <class T>
void DlList<T>::print()
{
    DlNode<T> *p;
    p=head->next;
    while( p!=head )
    {
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<endl;
}

int main()
{
    int a[10]={ 2,44,22,30,68,90,52,39,110,78 };
    DlList<int> test( a,10 );
    test.print();
    test.del(1);
    test.print();
    test.inst( 1,99 );
    test.print();
    return 0;
}

你可能感兴趣的:(双向循环链表类)