File tree Expand file tree Collapse file tree 1 file changed +22
-3
lines changed Expand file tree Collapse file tree 1 file changed +22
-3
lines changed Original file line number Diff line number Diff line change @@ -25,6 +25,20 @@ class LRUCache {
25
25
head->next = tail;
26
26
tail->prev = head;
27
27
}
28
+ // Destructor: Cleans up dynamically allocated resources
29
+ // to prevent memory leaks. Implemented if time permits
30
+ // during an interview.
31
+ ~LRUCache () {
32
+ // Delete all nodes in the linked list.
33
+ DoublyLinkedListNode* current = head;
34
+ while (current != nullptr ) {
35
+ DoublyLinkedListNode* nextNode = current->next ;
36
+ delete current;
37
+ current = nextNode;
38
+ }
39
+ // Clear the hashmap.
40
+ hashmap.clear ();
41
+ }
28
42
29
43
int get (int key) {
30
44
if (hashmap.find (key) == hashmap.end ()) {
@@ -41,15 +55,20 @@ class LRUCache {
41
55
// If a node with this key already exists, remove it from the
42
56
// linked list.
43
57
if (hashmap.find (key) != hashmap.end ()) {
44
- removeNode (hashmap[key]);
58
+ DoublyLinkedListNode* existingNode = hashmap[key];
59
+ removeNode (existingNode);
60
+ delete existingNode;
61
+ hashmap.erase (key);
45
62
}
46
63
DoublyLinkedListNode* node = new DoublyLinkedListNode (key, val);
47
64
hashmap[key] = node;
48
65
// Remove the least recently used node from the cache if adding
49
66
// this new node will result in an overflow.
50
67
if (hashmap.size () > capacity) {
51
- hashmap.erase (head->next ->key );
52
- removeNode (head->next );
68
+ DoublyLinkedListNode* lruNode = head->next ;
69
+ hashmap.erase (lruNode->key );
70
+ removeNode (lruNode);
71
+ delete lruNode;
53
72
}
54
73
addToTail (node);
55
74
}
You can’t perform that action at this time.
0 commit comments