用链表实现,当页面命中时就把页面提到列表最前面,未命中时把页面插入到列表最前面并移除链表最后一个节点。
#include "stdlib.h"
#include "stdio.h"
#define SEC_NUM 4 // cache size
#define PAGE_NUM 12 世态// page number
typedef struct Node {
char page;
struct Node *next;
} Node;
typedef struct Node *linkList;
// show current status of cache
void show(Node *cache){
Node *tmp = cache;
int i;
printf("Cache status:");
for (i = 0; i < SEC_NUM; i++){
printf("%c", tmp->page);
tmp = tmp->next;
}
printf("\n");
}
// return the pointer of the existing page in cache or NULL if not in cache
Node* isIncluded(Node *head, char page){
Node *tmp = head, *flag = NULL;
int i;
for (i = 0; i < SEC_NUM; i++){
if(tmp->next->page == page)
flag = tmp;
tmp = tmp->next;
}
return flag;
}
int main()
{
int i = 0, index = -1;
char pages[] = {'4','3','2','1','4','3','5','4','3','2','1','5'};
Node *head, *cache, *tmp, *tmp2;
int miss_num = 0;
float miss_ratio = 0;
// initialize the list
if ( (head = (linkList)malloc(sizeof(Node))) == NULL){
printf("Can not allocate memory.");
return 1;
}
head->page = '0';
head->next = NULL;
cache = head;
// assign values to cache
for (i = 0; i < SEC_NUM; i++){
if ((tmp = ((linkList)malloc(sizeof(Node)))) == NULL) {
printf("Can not allocate memory.");
return 1;
}
cache->next = tmp;
tmp->page = '0';
tmp->next = NULL;
cache = tmp;
}
show(head->next);
for (i = 0; i < PAGE_NUM; i++) {
// the page is already in cache
// move the page to the first position (right after head)
if ((tmp = isIncluded(head,pages[i])) != NULL) {
tmp2 = head->next;
head->next = tmp->next;
tmp->next = tmp->next->next;
head->next->next = tmp2;
}
// the page is not in cache
// insert the page to the first position, and remove the last node
else {
搜裤源 纯丛 miss_num ++;
tmp2 = head->next;
if ((head->next = (linkList)malloc(sizeof(Node))) == NULL){
printf("Can not allocate memory.");
return 1;
}
head->next->page = pages[i];
head->next->next = tmp2;
head->next->next->next->next->next = NULL; // assign NULL to the *next of the fourth nod (remove the last node)
}
show (head->next);
}
miss_ratio = (float)miss_num/PAGE_NUM;
printf("Number of misses is %d, and miss ratio is %f \n", miss_num, miss_ratio);
return 0;
}
73682-876-876-377