线性表描述字典

template<class K,class E>
struct pair
{
    K first;
    E second;   
};

template<class K,class E>
struct pairNode
{
    pair<K,E>element;
    pairNode<K,E>* next;
    pairNode(){};
    pairNode(pair<K,E>thePair,pair<K,E>* p)
    {
        element=thePair;
        next=p;
    }
};


template<class K,class E>
class dictionary
{
    public:
    virtual ~dictionary(){}
    virtual bool empty() const=0;
    virtual int size() const=0;
    virtual pair<const K,E>* find(const K&) const=0;
    virtual void erase(const K&)=0;
    virtual void insert(const pair<const K,E>&)=0;
};

template<class K,class T>
class sortedChain public:dictionary
{
    public:
    sortedChain(){firstNode=NULL;dSize=0;}; 
    bool empty() const;
    int size() const;
    pair<const K,E>* find(const K&) const;
    void erase(const K&)=0;
    void insert(const pair<const K,E>&);
    private:
    pair<K,E>* firstNode;
    int dSize;
};

template<class K,class E>
pair<const K,E>* sortedChain<K,E>::find(const K& theKey) const
{
    pairNode<K,E>* currentNode=firstNode;
    while(currentNode!=NULL&&currentNode->element.first!=theKey)
        currentNode=currentNode->next;

    if(currentNode!=NULL&&currentNode->element.first==theKey)
        return &currentNode->element;
    return NULL;
}

template<class K,class E>
void sortedChain<K,E>::insert(const pair<const K,E>& thePair)
{//往字典中插入thePair,覆盖已经存在的匹配的数对
pairNode<K,E>* p=firstNode,*tp=NULL;
while(p!=NULL&&p->element.first<thePair.first)
{
    tp=p;
    p=p->next;//tp在p的前一个位置
}
if(p!=NULL&&p->element.first==thePair.first)
{
    p->element.second=thePair.second;
    return;
}
//无匹配的数对,为pair建立新节点
pairNode<K,E>*newNode=new pairNode<K,E>(thePair,p)
//在tp之后插入新节点
if(tp==NULL) firstNode=newNode;
else 
tp->next=newNode;
dSize++;
return; 
}

template<class K,class E>
void sortedChain<K,E>::erase(const K& theKey)
{//删除关键字为theKey的数对
pair<K,E>* p=firstNode;
pair<K,E>* tp=NULL;

while(p!=NULL&&p->element.first<theKey)//如果p是第一个节点,那么第二个条件不会满足,tp仍然为NULL
{
    tp=p;
    p=p->element;
}
if(p!=NULL&& p->element.first==theKey)
{
    if(tp==NULL) firstNode=p->next;//p是第一个节点
    else
        tp->next=p->next;
    delete p;
    dSize--;
}

}

其实和之前的链表线性描述是一样的,只是这里面的基本结构为pairNode,pair. pair里面提供了两个元素,一个为键,一个为键值。

猜你喜欢

转载自blog.csdn.net/du_shuang/article/details/81198139
今日推荐