LRUCache java版实现

实现代码

import java.util.HashMap;
import java.util.Map;

public class LRUCache {
    static class ListNode{
        int key;
        int value;
        ListNode pre;
        ListNode next;

        public ListNode(int key,int value){
            this.key = key;
            this.value = value;
        }
        public ListNode(){}
    }

    static Map<Integer,ListNode> nodeMap;

    static int size;
    static int capacity;

    ListNode head;
    ListNode tail;

    public LRUCache(int capacity){
        nodeMap = new HashMap<>();
        this.capacity = capacity;
        head = new ListNode();
        tail = new ListNode();
        head.next = tail;
        tail.pre = head;
        size = 0;
    }

    public int get(int key){
        if(!nodeMap.containsKey(key)){
            return -1;
        }
        ListNode node = nodeMap.get(key);
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value){
        if(nodeMap.containsKey(key)){
            ListNode node = nodeMap.get(key);
            node.value = value;
            moveToHead(node);
            return;
        }
        if(size>=capacity){
            ListNode node = tail.pre;
            remove(node);
            nodeMap.remove(node.key);
            size--;
        }
        ListNode node = new ListNode(key,value);
        addToHead(node);
        nodeMap.put(key,node);
        size++;

    }

    public void remove(ListNode node){
        node.next.pre = node.pre;
        node.pre.next = node.next;
    }
    public void addToHead(ListNode node){
        node.next = head.next;
        node.pre = head.next.pre;
        head.next = node;
        node.next.pre = node;
    }

    public void moveToHead(ListNode node){
        remove(node);
        addToHead(node);
    }
}

测试代码

public void Test(){
        LRUCache lruCache = new LRUCache(2);
        lruCache.put(1,1);
        lruCache.put(2,2);
        System.out.println(lruCache.get(1));
        lruCache.put(3,3);
        System.out.println(lruCache.get(2));
        lruCache.put(4,4);
        System.out.println(lruCache.get(1));
        System.out.println(lruCache.get(3));
        System.out.println(lruCache.get(4));
}

输出

1
-1
-1
3
4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值