力扣146(雙向鏈表加哈希表)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

class LRUCache
{
public:

    struct Node
    {
    public:
        int val,key;
        Node *next,*pre;
        Node(int a,int b)
        {
            key=a;
            val=b;
            next=NULL;
            pre=NULL;
        }
        Node()
        {
            next=NULL;
            pre=NULL;
        }
    };
    Node *head,*tail;
    int Size=0;
    void Delete(Node *x)
    {
        x->next->pre=x->pre;
        x->pre->next=x->next;
        delete x;
        Size--;
    }

    void AddHead(Node *x)
    {
        x->next=head->next;
        head->next->pre=x;
        head->next=x;
        x->pre=head;
        Size++;
    }

    map<int,Node*> mp;
    int ceil;
    LRUCache(int capacity)
    {
        ceil=capacity;
        head=new Node();
        tail=new Node();
        head->next=tail;
        tail->pre=head;
    }

    int get(int key)
    {
        if(mp[key]==NULL)
            return -1;
        else
        {
            Node *tmp=mp[key];
            int a=tmp->val;
            Node *add=new Node(key,a);
            AddHead(add);
            Delete(mp[key]);
            mp[key]=add;
            return a;
        }
    }

    void put(int key, int value)
    {
        if(mp[key]!=NULL)
        {
            Node *tmp=mp[key];
            int a=value;
            Node *add=new Node(key,a);
            AddHead(add);
            Delete(mp[key]);
            mp[key]=add;
        }
        else
        {
            Node *a=new Node(key,value);
            if(Size<ceil)
            {
                AddHead(a);
                mp[key]=a;
            }
            else
            {
                mp[tail->pre->key]=NULL;
                Delete(tail->pre);
                mp[key]=a;
                AddHead(a);
            }
        }
    }

};

int main()
{

    LRUCache* obj = new LRUCache(2);
    obj->

}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章