defput(self, key, value): if self.capacity == 0: return
if key in self.map: # if this key exist in map node = self.map.get(key) # get this key self.dlist.remove(node) # remove the node with this key node.value = value # update the value of that node self.dlist.append(node) # add node to the tail else: if self.size == self.capacity: # if cache is full node = self.dlist.pop() del self.map[node.key] # delete the node at the head self.size -= 1 node = Node(key, value) self.dlist.append(node) # add new node to the tail self.map[key] = node self.size += 1
# delete head def__del_head(self): ifnot self.head: # if empty list return node = self.head # assign self.head to a new node if node.next: self.head = node.next self.head.prev = None node.next = None else: # only a head exist self.head = self.tail = None self.size -= 1 return node
# remove node in any position def__remove(self, node): # if node==None, remove tail by default ifnot node: node = self.tail if node == self.tail: self.__del_tail() elif node == self.head: self.__del_head() else: node.prev.next = node.next node.next.prev = node.prev self.size -= 1 return node
# APIs # pop node from head defpop(self): return self.__del_head()
# add node to the tail defappend(self, node): return self.__add_tail(node)
# add node to the head defappend_head(self, node): return self.__add_head(node)
defprint(self): p = self.head line = '' while p: line += '%s' % p p = p.next if p: line += '->' ifnot line: print("empty double linked list") print(line)