This structure is the inside a double linked list and map, the Key&dlinkedlistnode correspondence, do not have to search again
1 Public classLRUCache {2 classNode {3 intkey;4 intvalue;5 Node pre;6 Node Post;7 }8 9 Private intcount;Ten Private intcapacity; One PrivateMap<integer, node>map; A PrivateNode head, tail; - - PublicLRUCache (intcapacity) { the This. Capacity =capacity; - This. Count = 0; -Map =NewHashmap<integer, node>(); -Head =NewNode (); +Head.pre =NULL; -Tail =NewNode (); +Head.post =tail; ATail.pre =head; atTail.post =NULL; - } - - Private voidRemoveNode (node node) { -Node Prenode =Node.pre; -Node Postnode =Node.post; inPrenode.post =Postnode; -Postnode.pre =Prenode; to } + - Private voidAddNode (node node) { theNode.pre =head; *Node.post =Head.post; $Head.post.pre =node;Panax NotoginsengHead.post =node; - } the + PrivateNode Poll () { ANode Prenode =Tail.pre; the This. RemoveNode (Prenode); + returnPrenode; - } $ $ Private voidMovenodetohead (node node) { - This. RemoveNode (node); - This. AddNode (node); the } - Wuyi Public intGetintkey) { theNode node =Map.get (key); - if(Node! =NULL) { Wu This. Movenodetohead (node); - returnNode.value; About } $ return-1; - } - - Public voidSetintKeyintvalue) { A if( This. Map.containskey (Key)) { +Node node =Map.get (key); theNode.value =value; - This. Movenodetohead (node); $}Else { theNode node =NewNode (); theNode.key =key; theNode.value =value; the This. Map.put (key, node); -count++; in This. AddNode (node); the if(Count >capacity) { theNode Tailnode = This. Poll (); About This. Map.Remove (Tailnode.key); thecount--; the } the } + } -}
A little longer buy-in will find that they are riddled with mistakes:
1. See the type of return, get method return is int, do not return to node
2. Function name Variable name figure out
It is worth noting that the constructor inside the LRU, the 21st line, to pay attention to create tail, and then Head.post point to the past!! It's crazy to find this bug!!!.
146. LRU Cache