C++双向链表

template<class T>
class DLLNode
{
public:
    DLLNode()
    {
        next = prev = 0;
    }
    DLLNode(const T& el, DLLNode* n = 0, DLLNode * p = 0) {
        info = el; next = n; prev = p;
    }

    T info;
    DLLNode* next, * prev;

};
template<class T>
class DoublyLinkedList
{
public:
    DoublyLinkedList()
    {
        head = tail = 0;
    }
    
    void Add(const T&);
    T DeleteLast();

    bool isEmpty()
    {
        return head == 0;
    }

private:
    DLLNode<T>* head, * tail;
};

template<class T>
void DoublyLinkedList<T>::Add(const T& el)
{
    if (tail != 0)
    {
        tail = new DLLNode<T>(el, 0, tail);
        tail->prev->next = tail;
    }
    else
    {
        head = tail = new DLLNode<T>(el);
    }
}

template<class T>
T DoublyLinkedList<T>::DeleteLast()
{
    T el = tail->info;
    if (head == tail)
    {
        delete head;
        head = tail = 0;
    }
    else
    {
        tail = tail->prev;
        delete tail->next;
        tail->next = 0;
    }
    return el;
}

 

posted on 2019-08-11 23:34  迎着风追赶  阅读(187)  评论(0编辑  收藏  举报

导航