• c++初步实现的一个LRU


    #include<iostream>
    #include<map>

    using namespace std;

    typedef struct Node
    {
    int data;
    struct Node *next;
    struct Node(int element) :data(element),next(NULL) {};
    }node;

    node* inserts(node* proot, int data)
    {
    node *ptmp = new node(data);
    ptmp->next = proot;
    return ptmp;
    }

    node *deletenode(node* proot, int data)
    {
    node *res = proot;
    if (proot->data == data)
    {
    node *ptmp = proot;
    res = proot->next;
    delete ptmp;

    }
    else if(proot->next!=NULL&&proot->next->data != data)
    {
    proot = proot->next;
    }
    else if(proot->next!=NULL&&proot->next->data==data)
    {
    node *ptmp = proot->next;
    proot->next = ptmp->next;
    delete ptmp;
    }
    return res;
    }
    node* pop(node *proot)
    {
    node* res = proot;
    if (proot == NULL)
    return res;
    node *ptmp = proot->next;
    while (ptmp->next)
    {
    proot = ptmp;
    ptmp = ptmp->next;
    }
    if (ptmp->next == NULL)
    {
    proot->next = NULL;
    delete ptmp;
    }
    return res;
    }
    void printfd(node *proot)
    {
    while (proot)
    {
    cout << proot->data << " ";
    proot = proot->next;
    }
    cout << endl;
    }


    class LRU {
    public:
    LRU(int length) :root(NULL),len(length) {};
    void insert(int data);
    void printfs() {
    printfd(root);
    }
    private:
    node *root;
    map<int, int> vec;
    int len;
    };

    void LRU::insert(int data)
    {
    if (vec.count(data) > 0)
    {
    root = deletenode(root, data);
    root = inserts(root, data);
    }
    else
    {
    if (vec.size() >= len)
    {
    root = pop(root);
    root = inserts(root, data);
    vec[data] = data;
    }
    else
    {
    root = inserts(root, data);
    vec[data] = data;
    }
    }
    }


    int main()
    {
    LRU test(5);
    test.insert(1);
    test.insert(2);
    test.insert(3);
    test.printfs();
    test.insert(4);
    test.insert(5);
    test.printfs();
    test.insert(6);
    test.printfs();
    test.insert(7);
    test.insert(8);
    test.insert(9);
    test.printfs();
    }

  • 相关阅读:
    前端学习之路,新手必看
    css常用的属性方法 上篇
    H5音乐播放器源码地址
    H5音乐播放器源码共享
    H5音乐播放器【歌单列表】
    (1)H5实现音乐播放器【正在播放-歌词篇】
    JS 对数组的操作集锦(基础)
    完整的淘宝页面模板
    一次上机试题(面向对象)
    python select方法的使用
  • 原文地址:https://www.cnblogs.com/break-python/p/5932344.html
Copyright © 2020-2023  润新知