1+ //双向链表的节点
2+ class Node {
3+ public int key ;
4+ public int val ;
5+ public Node pre ;//指向前面的指针
6+ public Node next ;//指向后面的指针
7+ public Node (int key ,int value ){
8+ this .val =value ;
9+ this .key =key ;
10+ }
11+ }
12+ class LRUCache {
13+ int capacity ;//容量
14+ Node head ;//双向链表的头,维护这个指针,因为set,get时需要在头部操作
15+ Node end ;//双向链表的尾,set时,要是满了,需要将链表的最后一个节点remove
16+ HashMap <Integer ,Node > map =new HashMap <Integer ,Node >();//hash表
17+ public LRUCache (int capacity ) {
18+ this .capacity =capacity ;
19+ }
20+ //添加,删除尾部,插入头部的操作
21+ public void remove (Node node ){
22+ Node cur =node ;
23+ Node pre =node .pre ;
24+ Node post =node .next ;
25+ if (pre ==null ){//说明cur是头部节点
26+ head =post ;
27+ }
28+ else pre .next =post ;//更新指针,删除
29+ if (post ==null ){//说明cur是最后的节点
30+ end =pre ;
31+ }
32+ else post .pre =pre ;
33+ }
34+ public void setHead (Node node ){
35+ //直接插入
36+ node .next =head ;
37+ node .pre =null ;
38+ if (head !=null ) head .pre =node ;//防止第一次插入时为空
39+ head =node ;
40+ if (end ==null ) end =node ;
41+ }
42+ public int get (int key ) {
43+ if (map .containsKey (key )){
44+ //需要把对应的节点调整到头部
45+ Node latest =map .get (key );
46+ remove (latest );
47+ setHead (latest );
48+ //返回value
49+ return latest .val ;
50+ }
51+ else return -1 ;
52+ }
53+
54+ public void put (int key , int value ) {
55+ if (map .containsKey (key )){//这个key原来存在
56+ //只需要把key对应的node提到最前面,更新value
57+ Node oldNode =map .get (key );
58+ oldNode .val =value ;
59+ remove (oldNode );
60+ setHead (oldNode );
61+ }
62+ else {
63+ //这个key原来不存在,需要重新new出来
64+ Node newNode =new Node (key ,value );
65+ //接下来要考虑容量
66+ if (map .size ()<capacity ){
67+ setHead (newNode );
68+ map .put (key ,newNode );
69+ }
70+ else {
71+ //容量不够,需要先将map中,最不常使用的那个删除了删除
72+ map .remove (end .key );
73+ //接下来更新双向链表
74+ remove (end );
75+ setHead (newNode );
76+ //放入新的
77+ map .put (key ,newNode );
78+ }
79+ }
80+ }
81+ }
82+
83+ /**
84+ * Your LRUCache object will be instantiated and called as such:
85+ * LRUCache obj = new LRUCache(capacity);
86+ * int param_1 = obj.get(key);
87+ * obj.put(key,value);
88+ */
0 commit comments