双向链表结构衍生出来的LRU缓存(来自leetcode题目)

 

import java.util.HashMap;

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

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

Follow up:
Could you do both operations in O(1) time complexity?

LRUCache cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4
 */
class Node{//双向链表
    int key;
    int value;
    Node next;
    Node pre;
    public Node(int key,int value,Node pre, Node next){
        this.key = key;
        this.value = value;
        this.pre = pre;
        this.next = next;
    }
}
public class LRUCache {
    int capacity;
    int count;//cache size
    Node head;
    Node tail;
    HashMap<Integer,Node>hm;
    public LRUCache(int capacity) { //only initial 2 Node is enough, head/tail
        this.capacity = capacity;
        this.count = 2;
        this.head = new Node(-1,-1,null,null);
        this.tail = new Node(-2,-2,this.head,null);
        this.head.next = this.tail;
        hm = new HashMap<Integer,Node>();
        hm.put(this.head.key, this.head);
        hm.put(this.tail.key, this.tail);
    }
    
    public int get(int key) {
        int value = -1;
        if(hm.containsKey(key)){
            Node nd = hm.get(key);
            value = nd.value;
            detachNode(nd); //detach nd from current place
            insertToHead(nd); //insert nd into head
        }
        return value;
    }
    
    public void put(int key, int value) {
        if(hm.containsKey(key)){ //update
            Node nd = hm.get(key);
            nd.value = value;
            //move to head
            detachNode(nd); //detach nd from current place
            insertToHead(nd); //insert nd into head
        }else{ //add
            Node newNd = new Node(key,value,null,this.head);
            this.head.pre = newNd; //insert into head
            this.head = newNd;
            hm.put(key, newNd); //add into hashMap
            this.count ++;
            if(this.count > capacity){ //need delete node
                removeNode();
            }
        }
    }
    //common func
    public void insertToHead(Node nd){//最后结果为B->C->A
        //A->C->B,当前节点为C,头节点为A
        //头节点的前一节点插入...........
        this.head.pre = nd;
        nd.next = this.head;
        nd.pre = null;
        this.head = nd;
    }
    public void detachNode(Node nd){
        //当前节点为nd,头节点为head
        //比如 A->B->C,头节点为A,当前节点为B
        //当前节点的前一节点指向当前节点的下一节点 A->C 
        nd.pre.next = nd.next;
        if(nd.next!=null){
            //若当前节点的下一节点存在,则当前节点的下一节点的前一节点为当前节点的前一节点
            nd.next.pre = nd.pre;
            //否则,尾节点为当前节点的前一节点,即A->C->B
        }else{
            this.tail = nd.pre;
        }
    }
    public void removeNode(){ //remove from tail
        int tailKey = this.tail.key;
        this.tail = this.tail.pre;
        this.tail.next = null;
        hm.remove(tailKey);
        this.count --;
    }
    public void printCache(){
        System.out.println("\nPRINT CACHE ------ ");
        System.out.println("count: "+count);
        System.out.println("From head:");
        Node p = this.head;
        while(p!=null){
            System.out.println("key: "+p.key+" value: "+p.value);
            p = p.next;
        }
        System.out.println("From tail:");
        p = this.tail;
        while(p!=null){
            System.out.println("key: "+p.key+" value: "+p.value);
            p = p.pre;
        }
        
    }
    
    public static void main(String[] args){
        LRUCache lc = new LRUCache(3);
        System.out.println("LRUCache初始化状态,Cache初始容量是2");
        lc.printCache();
        lc.put(1, 1);
        lc.put(2, 2);
        lc.put(3, 3);
        System.out.println("第一次put操作后的结果");
        lc.printCache();
        
        lc.get(2);
        System.out.println("第一次get(key==2)操作后的结果");
        lc.printCache();
        
        lc.put(4, 4);
        System.out.println("第二次put(key==4)操作后的结果,容量已满,替换最不常用的key和value");
        lc.printCache();
        
        lc.get(1);
        System.out.println("第二次get(key==1)操作后的结果");
        lc.printCache();
        
        lc.put(3, 33);
        System.out.println("第三次put(key==3)操作后的结果,替换已有key的值");
        lc.printCache();    
    }
}


 

 

双向链表:

class Node{
    int key;
    int value;
    Node next;//下一节点
    Node pre;//前一节点
    public Node(int key,int value,Node pre, Node next){
        this.key = key;
        this.value = value;
        this.pre = pre;
        this.next = next;
    }
}

图解结构如下,

 

插入:假设要在key=1和key=2之间插入一个节点key=x

则,

Node k1,k2,kx;

已知k2,kx

kx.next = k2;

kx.pre = k2.pre;

k2.pre.next = kx;

----------------------------------

private Node head = new Node(null);

private void addBefore(Node newNode, Node node){

newNode.next = node;

newNode.pre = node.pre;

Node.pre.next = newNode;

}

 

 

单链表的反转:

static ListNode reverseLinkedList(ListNode node) {
        ListNode previousNode = null;
        ListNode currentNode = node;
        ListNode headNode = null;
        while (currentNode != null) {
            ListNode nextNode = currentNode.next;
            if (nextNode == null) {
                headNode = currentNode;
            }
            currentNode.next = previousNode;
            previousNode = currentNode;
            currentNode = nextNode;
        }
        return headNode;
    }

双向链表操作可以参看LinkedList类中的构造方法(增删查找):

https://crowhawk.github.io/2017/08/26/collections_1/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值