- 创建一个双向链表,有key ,value, 前驱节点 和后继节点
class Node{
int key;
int value;
Node next;
Node pre;
Node(int key,int value){
this.key=key;
this.value=value;
}
}
- 在主类里面创建四个实例字段
private int capacity;
private HashMap<Integer, Node> map;
private Node head;
private Node tail;
- put方法的实现,从hashmap中直接取值,如果不为null,则将node的值更新,并把该节点利用moveNodeToTail方法移动到链表末尾,如果为null,则创建一个新的node结点,然后计算当前map的大小是否已经到达门槛值,需要移除队头元素,调用removeHead方法,进行移除,然后调用addLast方法,将新的node结点加入链表,并且加入hashmap中
public void put(int key, int value) {
Node node=map.get(key);
if(node!=null){
node.value=value;
moveNodeToTail(node);
return;
}
Node tmp=new Node(key,value);
if(map.size()==capacity){
Node delHead = removeHead();
map.remove(delHead.key);
}
addLast(tmp);
map.put(key,tmp);
return;
}
- get方法实现,map.get(key)的值如果为null的话,就返回-1,如果不等于null,则将该节点利用moveNodeToTail方法移动到末尾,并且返回当前结点的值
public int get(int key) {
Node node=map.get(key);
if(node!=null){
moveNodeToTail(node);
return node.value;
}
return -1;
}
- 附加方法
addLast方法:首先判断node是否为null,不为null的话,判断当前的头结点和尾结点是否为null,为null,就创建头尾指针,不为null,则通过尾部节点连接新的结点,
moveNodeToTail方法:首先找出特殊情况,node为头部结点和尾部节点的情况
为尾部节点就不需要更新,为头部结点的话,head=node.next;head.pre=null;
removeHead方法:判断head是否为null,然后判断head==tail,重新定义,
否则利用链表的移除法则移除就行了
public void addLast(Node node){
if(node==null)return;
if(head==null){
head=node;
tail=node;
}else{
tail.next=node;
node.pre=tail;
tail=node;
}
}
public Node removeHead() {
if(head==null){
return null;
}
Node res=head;
if(head==tail){
head=null;
tail=null;
}else{
head=head.next;
head.pre=null;
res.next=null;
}
return res;
}
public void moveNodeToTail(Node node){
if(tail==node)return;
if(head==node){
head=node.next;
head.pre=null;
}else{
node.pre.next=node.next;
node.next.pre=node.pre;
}
node.pre=tail;
node.next=null;
tail.next=node;
tail=node;
}