-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru_cache.cpp
More file actions
86 lines (80 loc) · 1.64 KB
/
lru_cache.cpp
File metadata and controls
86 lines (80 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <map>
using namespace std;
typedef struct node {
int data;
struct node* next;
struct node* prev;
}node;
typedef struct s_lru {
int size;
map <int, node*> mp;
node* head;
}s_lru;
node* getNode(int page) {
node* temp = (node *)malloc(sizeof(node));
temp->data=page;
temp->next=temp;
temp->prev=temp;
return temp;
}
void ca_refer(int page, struct s_lru & lru) {
map<int,node *>::iterator it = lru.mp.find(page);
if(it!=lru.mp.end()) {
node* temp=it->second;
node* prev=temp->prev;
prev->next = temp->next;
temp->next->prev = prev;
free(temp);
temp = getNode(page);
temp->next = lru.head;
temp->prev=lru.head->prev;
lru.head->prev->next=temp;
lru.head->prev=temp;
lru.head=temp;
lru.mp[page]=temp;
}
else {
if(lru.mp.size() >= lru.size) {
node* temp = lru.head->prev;
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
free(temp);
}
node* temp = getNode(page);
if(lru.mp.size() == 0) {
lru.mp[page]=temp;
lru.head=temp;
return;
}
temp->next = lru.head;
temp->prev = lru.head->prev;
lru.head->prev->next=temp;
lru.head->prev = temp;
lru.head = temp;
lru.mp[page] = temp;
}
}
void display(node* head) {
node* temp = head;
while(temp->next != head) {
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<temp->data<<endl;
}
int main() {
struct s_lru s1;
int n;
cin>>n;
s1.size=n;
s1.head=NULL;
ca_refer(1,s1);
ca_refer(2,s1);
ca_refer(3,s1);
ca_refer(1,s1);
ca_refer(4,s1);
ca_refer(5,s1);
display(s1.head);
return 0;
}