-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU.c
53 lines (44 loc) · 1.14 KB
/
LRU.c
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
typedef struct {
int key;
int value;
} ITEM_S;
typedef struct {
int capacity;
ITEM_S *pstItem;
} Solution;
Solution* SolutionCreate(int capacity) {
Solution* obj = malloc(sizeof(Solution));
obj->capacity = capacity;
obj->pstItem = malloc(sizeof(ITEM_S) * capacity);
memset(obj->pstItem, 0, sizeof(ITEM_S) * capacity);
return obj;
}
int SolutionGet(Solution* obj, int key) {
ITEM_S *pstItem = obj->pstItem;
for(int i = 0; i < obj->capacity; i++) {
if (key == pstItem[i].key) {
int value = pstItem[i].value;
for(int j = i - 1; j >= 0; j--) {
ITEM_S tmp = pstItem[i];
pstItem[i] = pstItem[j];
pstItem[j] = tmp;
}
return value;
}
}
return -1;
}
void SolutionSet(Solution* obj, int key, int value) {
ITEM_S *pstItem = obj->pstItem;
for(int j = obj->capacity - 1; j > 0; j--) {
pstItem[j] = pstItem[j - 1];
}
pstItem[0].key = key;
pstItem[0].value = value;
}
void SolutionFree(Solution* obj) {
if (obj != NULL) {
free(obj->pstItem);
free(obj);
}
}