C++链表与键值对

时间:2024-03-22 22:37:14

《算法》一书中,在算法3.1中提到了Map的实现,这里根据书上的思想,用单向链表简单写了写。

#ifndef SEQUENTIAL_H
#define SEQUENTIAL_H
template<class K, class V>
class Link
{
private:
    class Node
    {
    public:
        K key=;
        V value=;
        Node *next=nullptr;
    public:
        Node(K, V, Node*);
        Node(){};
    };
private:
    Node *first;
    int _length;
    int _capicty;
public:
    Link();
    V& get(K key);
    void put(K key, V value);
    int Size() const;
    int Capicty() const;
    bool Delete(K key);
    ~Link();
};

template<class K, class V>
Link<K, V>::Node::Node(K key, V value, Node* node)
{
    this->key = key;
    this->value = value;
    next = node;
}
template<class K, class V>
V& Link<K, V>::get(K key)
{
    Node *x = first;
    ; i < _length&& x != nullptr; i++)
    {
        if (x->key == key) return x->value;
        x = x->next;
    }
}
//如果没有K,则在链表尾加入新的键值对
template<class K, class V>
void Link<K, V>::put(K key, V value)
{
    Node *x = first;
    bool flag = false;
    ; i < _length; i++)
    {
        if (x->key == key) { x ->value = value; flag = true; break; }
        x = x->next;
    }
    if (!flag)
    {
         >= _capicty)
        {
            Node *m = first;
            _capicty *= ;
            Node **n = new Node*[_capicty];
            ; i < _capicty; i++)
            {
                n[i] = new Node();
            }
            ; i < _capicty - ; i++)
            {
                n[i]->next = n[i + ];
            }
            ; i < _capicty && m!=nullptr; i++)
            {
                n[i] =  m;
                m = m->next;
            }
            delete[] first;
            first = n[];
        }
        int l = _length;
        Node *y = first;
        while (l)
        {
            y = y->next;
            l--;
        }
        y->value = value;
        y->key = key;
        y->next = y->next;
        _length++;
    }

}
template<class K, class V>
Link<K, V>::~Link()
{
    if (first != nullptr) delete[] first;
}
template<class K, class V>
Link<K, V>::Link()
{
    Node** n = ];
    _capicty = ;
    _length = ;
    ; i <  ; i++)
    {
        n[i] = new Node();
    }
    ; i < -; i++)
    {
        n[i]->next = n[i+];
    }
    first = n[];
}
template<class K, class V>
int Link<K, V>::Size() const
{
    return _length;
}

//当前链表容量
template<class K, class V>
int Link<K, V>::Capicty() const
{
    return _capicty;
}
template<class K, class V>
bool Link<K, V>::Delete(K key)
{
    bool flag = false;

    Node* n = first->next;
    Node* b = first;
    if (b->key == key)
    {
        _length--;
        first = first->next;
        return true;
    }
    ; i < _length; i++)
    {
        if (n->key == key)
        {
            b->next = n->next;
            _length--;
            flag = true;
            break;
        }
        b = b->next;
        n = n->next;
    }
    return flag;
}
#endif

相关文章