有序链表实现集合的抽象数据类型

template<class T>
struct SetNode
{
    T data;
    SetNode<T>* link;
    SetNode():link(NULL) {}
    SetNode(const T& x, SetNode<T>* next = NULL):data(x), link(next) {}
};

template<class T>
class LinkedSet
{
    public:
        LinkedSet() {first_ = last_ = new SetNode<T>;}
        LinkedSet(LinkedSet<T>& rhs);
        ~LinkedSet<T>() {makeEmpty(); delete first_;}
        void makeEmpty();
        bool addMember(const T& x);
        bool delMember(const T& x);
        LinkedSet<T>& operator = (const LinkedSet<T>& rhs);
        LinkedSet<T>& operator + (const LinkedSet<T>& rhs);
        LinkedSet<T>& operator - (const LinkedSet<T>& rhs);
        LinkedSet<T>& operator * (const LinkedSet<T>& rhs);
        bool Contains(const T& x);
        bool operator == (const LinkedSet<T>& rhs);
        bool Min(T& x);    // 返回集合最小元素的值
        bool Max(T& x);    // 返回集合最大元素的值
        bool subSet(const LinkedSet<T>& rhs);
    private:
        SetNode<T>* first_, last_;
};

template<class T>
LinkedSet<T>::LinkedSet(LinkedSet<T>& rhs)
{
    SetNode<T>* srcptr = rhs.first_->link;
    first_ = last_ = new SetNode<T>;
    while(srcptr != NULL)
    {
        last_->link = new SetNode<T>(srcptr->data); // 以rhs的结点为内容创建一个新结点
        last_ = last_->link;                        // first不变,改变last
        srcptr = srcptr->link;                      // 循环复制rhs的每个结点至*this
    }
    last_->link = NULL;
}

template<class T>
bool LinkedSet<T>::Contains(const T& x)
{
/*    SetNode<T>* tmp = first_->link;
    while(tmp != NULL)
    {
        if(tmp->data == x)
            return true;
    }
    return false;
*/
    SetNode<T>* tmp = first_->link;
    while(tmp != NULL && tmp->data < x)
    {
        tmp = tmp->link;
    }
    if(tmp !=NULL && tmp->data == x)
        return true;
    return false;
}

template<class T>
bool LinkedSet<T>::addMember(const T& x)
{
    SetNode<T>* tmp = first_->link;
    SetNode<T>* tmp1 = 0;
    while(tmp != NULL && tmp->data < x)
    {
        tmp1 = tmp;
        tmp = tmp->link;
    }

    if(tmp->data == x)
        return false;
    else if(tmp != NULL)
    {
        SetNode<T>* p = new SetNode<T>(x);
        p->link = tmp1->link;
        tmp1->link = p;
        return true;
    }
    else if(tmp == NULL)
    {
        SetNode<T>* p = new SetNode<T>(x);
        last_->link = p;
        last_ = p;
        return true;
    }
}

原文地址:https://www.cnblogs.com/kex1n/p/2286588.html