栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构(四)字典

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构(四)字典

数据结构(四)字典
  • 字典--c++实现
    • 字典原型(链表描述)
    • Dictionary类的实现

字典–c++实现 字典原型(链表描述)

在Dictionary.h文件中定义了节点,声明了字典类的原型

template
struct node {
    K key;
    E value;
    node *next;
};

template
class Dictionary {
private:
    node *head;
    int size;
public:
    Dictionary();

    ~Dictionary();

    bool isEmpty() const;

    int getSize() const;

    node *find(const K&) const;

    void del(const K&);

    void insert(const node&);
};
Dictionary类的实现
#include "Dictionary.h"

template
Dictionary::Dictionary() {
    head = nullptr;
    size = 0;
}

template
Dictionary::~Dictionary() {
    node *pd = head;
    while (pd->next != nullptr){
        node *p = pd;
        pd = pd->next;
        delete p;
    }
    delete pd;
}

template
bool Dictionary::isEmpty() const {             //判断字典是否为空
    return size == 0;
}

template
int Dictionary::getSize() const {               //返回字典元素个数
    return size;
}

template
node *Dictionary::find(const K & key) const {   //返回匹配关键字的节点指针
    node* pd = head;                       //如果匹配失败则返回nullptr
    while (pd != nullptr && pd->key != key){
        pd = pd->next;
    }
    if(pd != nullptr && pd->key == key)
    return pd;
    else return nullptr;
}

template
void Dictionary::del(const K & key) {          //删除对应关键字的元素
    node* pd = head;
    while (pd->key != key){
        pd = pd->next;
    }
    pd->key = pd->next->key;
    pd->value = pd->next->value;
    node* p = pd->next;
    pd->next = p->next;
    delete p;
    size -- ;
}

template
void Dictionary::insert(const node< K, E> & nd) { //插入字典元素
    if(head == nullptr){
        head = new node;
        head->key = nd.key;
        head->value = nd.value;
        head->next = nullptr;
    } else{
        node *nod = head;
        while (nod->next != nullptr){
            nod = nod->next;
        }
        nod -> next = new node;
        nod->next->next = nullptr;
        nod->next->key = nd.key;
        nod->next->value = nd.value;
    }
    size++;
}

测试程序如下:

#include 
int main(){
    Dictionary dictionary;
    for (int i = 0; i < 10; i++) {
        node n ;
        n = {i,i, nullptr};
        dictionary.insert(n);
    }
    std::cout << "key = 3 value = " << dictionary.find(3)->value << std::endl;
    std::cout << "size = " << dictionary.getSize() << std::endl;
    dictionary.del(4);
    std::cout << "size = " << dictionary.getSize() << std::endl;
    return 0;
}

测试结果:

key = 3 value = 3
size = 10
size = 9
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1018485.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号