最近最少用(LRU)虚拟存储管理页面淘汰算法(C)

#include  
#include 
#include 

int pageMissingNum = 0;

typedef struct Node {
    struct Node *pre, *next;
    int pageNumber; 
} Node;

typedef struct Queue {
    int count;
    int totalPage;
    Node *head, *end;
} Queue;

typedef struct Hash {
    Node* *arry;
} Hash;

Node* createNode(int pageNumber) {
    Node* n = (Node*) (malloc(sizeof(Node)));
    n->pageNumber = pageNumber;
    n->pre = n->next = NULL;

    return n;
}

Queue* createQueue(int totalPage) {
    Queue* q = (Queue*) (malloc(sizeof(Queue)));
    q->count = 0;
    q->totalPage = totalPage;
    q->head = q->end = NULL;

    return q;
}

Hash* createHash(int capacity) {
    Hash* h = (Hash*) (malloc(sizeof(Hash)));
    h->arry = (Node**) (malloc(sizeof(Node*) * capacity));
    
    for (int i = 0; i < capacity; i++) {
        h->arry[i] = NULL;
    }
    return h;
}

void deleteQueue(Queue* q, Hash* h) {
    Node *n = q->end;
    h->arry[n->pageNumber] = NULL;
    q->end = n->pre;
    n->pre->next = NULL;
    q->count--;
    printf("eliminate: %d \n", n->pageNumber);
    free(n);
}

void addQueue(Queue* q, Hash* h, int pageNumer) {
    Node* n = createNode(pageNumer);

    if (q->count == 0) {
        q->head = q->end = n;
    } else {
        n->next = q->head;
        q->head->pre = n;
        q->head = n;
    }
    
    h->arry[pageNumer] = n;
    q->count++;
}

void moveQueue(Queue* q, Hash* h, int pageNumer) {
    if (q->count == 1) {
        return;
    }

    Node* n = h->arry[pageNumer];
    if (q->head == n) {
        return;
    }

    if (q->end == n) {
        q->end = n->pre;
        n->pre->next = NULL;
    } else {
        n->pre->next = n->next;
        n->next->pre = n->pre;
    }
    n->pre = NULL;
    n->next = q->head;
    q->head->pre = n;
    q->head = n;
}

void lruProcess(Queue* q, Hash* h, int pageNumer) {
    if (h->arry[pageNumer] != NULL) {
        moveQueue(q, h, pageNumer);
    } else {
        pageMissingNum++;
        if (q->count == q->totalPage) {
            deleteQueue(q, h);
        }
        addQueue(q, h, pageNumer);
    }
}

void main() {
    char s[100];
    int totalPage;
    printf("Please enter the number of pages owned by the process: ");
    scanf("%d", &totalPage);

    printf("Please enter an access string: ");
    scanf("%s", s);

    Queue* q = createQueue(totalPage);
    Hash* h = createHash(100);

    for (int i = 0, len = strlen(s); i < len; i++) {
        lruProcess(q, h, s[i] - '0');
    }

    printf("Number of pages missing: %d \n", pageMissingNum);
}

你可能感兴趣的:(算法,操作系统)