[LeetCode]LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

思考:第一次遇到这种题目,说实话我实在构造不出这么好的数据结构:map+双向链表。

struct Node{

    int key;

    int value;

    Node *pre;

    Node *next;

    Node(int a,int b):key(a),value(b),pre(NULL),next(NULL){};

};//双向链表数据结构



class LRUCache{

private:

    int maxsize;

    Node *head;//链表头结点

    Node *tail;//链表尾结点

    map<int,Node*> m;

    

public:

    LRUCache(int capacity) {

        maxsize=capacity;

        head=NULL;

        tail=NULL;

        m.clear();

    }

    

    int get(int key) {

        map<int,Node*>::iterator iter=m.find(key);

        if(iter!=m.end())//找到key返回value,将结点移到链表头部

        {

            move(iter->second);

            return iter->second->value;

        }

        else return -1;

    }

    

    void set(int key, int value) {

        map<int,Node*>::iterator iter=m.find(key);

        if(iter!=m.end())//已存在key

        {

            Node *p=iter->second;

            p->value=value;

            move(p);

        }

        else//不存在key

        {

            if(m.size()==maxsize)//链表满删除尾结点

            {

                iter=m.find(tail->key);

                m.erase(iter);

                Node *p=tail;

                if(p->pre==NULL) head=NULL; 

                else p->pre->next=NULL;

				tail=tail->pre;

                delete p;

            }

            insert(key,value);

        }

    }

    

    void insert(int key,int value)//插入到头结点

    {

        Node *node=new Node(key,value);

        if(head==NULL) head=tail=node;

        else

        {

			head->pre=node;

            node->pre=NULL;

            node->next=head;            

            head=node;

        }

        m.insert(make_pair(key,node));

    }

    

    void move(Node *node)//移动到头结点

    {

        if(node==head) return;

        if(node==tail) tail=node->pre;

        node->pre->next=node->next;

        if(node->next!=NULL) node->next->pre=node->pre;

        node->pre=NULL;

        node->next=head;

        head->pre=node;

        head=node;

    }

};

  

你可能感兴趣的:(LeetCode)