-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU-Cache.cpp
86 lines (73 loc) · 1.38 KB
/
LRU-Cache.cpp
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<bits/stdc++.h>
using namespace std;
struct QNode{
QNode *prev,*next;
int pageNumber;
};
struct Queue{
int capacity,count;
QNode *front,*rear;
}Q;
QNode *hashTable[10];
void initialise(int n){
Q.capacity=n;
Q.count=0;
Q.front=Q.rear=NULL;
for(int i=0;i<10;i++){
hashTable[i]=NULL;
}
}
QNode* newnode(int n){
QNode *p = new QNode;
p->pageNumber = n;
p->prev=p->next=NULL;
return p;
}
void deleteNode(QNode *ptr){
if(ptr==Q.rear) Q.rear = ptr->prev;
if(ptr->prev) ptr->prev->next = ptr->next;
if(ptr->next) ptr->next->prev = ptr->prev;
delete ptr;
hashTable[ptr->pageNumber] = NULL;
Q.count--;
}
void insert(int n){
QNode *p = newnode(n);
if(Q.capacity==Q.count)
deleteNode(Q.rear);
p->next = Q.front;
if(Q.front!=NULL)
Q.front->prev=p;
else Q.rear=p;
Q.front = p;
Q.count++;
hashTable[n] = p;
}
void refPage(int n){
if(hashTable[n]==NULL){
insert(n);
return;
}
if(hashTable[n]==Q.front) return;
QNode *ptr = hashTable[n];
deleteNode(ptr);
insert(n);
}
void print(){
QNode *p=Q.front;
while(p) {
cout<<p->pageNumber << " ";
p=p->next;
}
cout<<endl;
}
int main(){
initialise(3);
refPage(1);
refPage(2);
refPage(3);
refPage(2);
refPage(4);
refPage(1);
print();
}