C++双向链表的实现

#include<iostream>
using namespace std;
template <class T>
struct DLNode
{
    T Data;///数据域
    DLNode<T> * left,* right;///指针域
    DLNode<T>()
    {
        left=right=NULL;   ///构造函数
    }
    DLNode<T>(const T& item,DLNode<T> *L=NULL,DLNode<T> *R=NULL):Data(item),left(L),right(R) {}
};
template <class T>
class DLList
{
private:
    DLNode<T>* head;
    DLNode<T>* currptr;
    int length;
public:
    DLList<T>();///只含哨位结点的空链表
    DLList<T>(const T& item);///含有一个结点与哨位结点的链表
    ~DLList<T>();
    int GetLength(void)const
    {
        return length;
    }
    bool IsEmpty() const
    {
        return length==0;
    }
    bool Insert(int,const T&);
    bool Delete(int);
    void Print(void);
};

template <class T>
DLList<T>::DLList()
{
    head=new DLNode<T>();
    length=0;
    currptr=head;
};
template <class T>
DLList<T>::DLList(const T& item)
{
    head=new DLNode<T>();
    currptr=new DLNode<T>(item);
    head->right=currptr;
    currptr->left=head;
    length=1;
}
template <class T>
DLList<T>::~DLList()
{
    while(IsEmpty())
    {
        currptr=head->right;
        head->right=currptr->right;
        currptr->right->left=head;
        delete currptr;
    }
    delete head;
}
template <class T>
bool DLList<T>::Insert(int k,const T& item)
{
    if(k<0||k>length)
        return false;
    currptr=head;
    for(int i=0; i<k; ++i)
    {
        currptr=currptr->right;
    }
    DLNode<T> * temp=new DLNode<T>(item,currptr,currptr->right);
    currptr->right=temp;
    if(temp->right!=NULL)
        temp->right->left=temp;
    length++;
    return true;
}
template <class T>
bool DLList<T>::Delete(int k)
{
    if(k<0||k>length||IsEmpty())
        return false;
    currptr=head;
    for(int i=0; i<k; ++i)
        currptr=currptr->right;
    DLNode<T> *temp=currptr;
    currptr=temp->left;
    if(temp->right!=NULL)///删除中间结点
    {
        currptr->right=temp->right;
        temp->right->left=currptr;
    }
    else///删除尾结点
    {
        currptr->right=NULL;
    }
    delete temp;
    length--;
}
template <class T>
void DLList<T>::Print(void)
{
    currptr=head;
    for(int i=0; i<length; ++i)
    {
        currptr=currptr->right;
        cout<<currptr->Data<<"<->";
    }
    cout<<endl;
}


///实例
int main()
{
    DLList<int> list(0);
    list.Print();
    ///尾插
    for(int i=4; i<=7; ++i)
        list.Insert(list.GetLength(),i);
    list.Print();
    ///头插
    for(int i=1; i<=3; ++i)
        list.Insert(0,i);
    list.Print();
    ///删除尾
    list.Delete(list.GetLength());
    list.Print();
    ///删除头(0结点为哨位结点,1结点为头结点)
    list.Delete(1);
    list.Print();
    return 0;
}

  

posted @ 2019-02-22 14:33  大大维  阅读(174)  评论(0编辑  收藏  举报