页面置换算法-LRU(Least Recently Used)c++实现

最近最久未使用(LRU)置换算法

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <assert.h>

using namespace std;
const int Maxn = 1500;

typedef struct Page_Node{
    struct Page_Node *next;
    int page_id;
    Page_Node(int v){page_id = v;}
}*PNode, Node;

class LRU{
public:
    LRU(int num):blocks_limit(num){
        head = NULL;
    }
    
    ~LRU(){
        delete head;
    }
    
    void update_order(int page_id){
        PNode p = head, last_node = NULL;
        while(p){
            if(p -> page_id == page_id){
                PNode next_node = p -> next;
                p -> next = head;
                if(last_node){
                    last_node -> next = next_node;
                }head = p;
                break;
            }
            last_node = p;
            p = p -> next;
        }
    }

    void insert_page(int page_id){
        PNode new_node = new Node(page_id);
        PNode tmp = head;
        head = new_node;
        head -> next = tmp;
        existed[page_id] = 1;
    }

    void delete_tail_page(){
        assert(NULL != head);
        PNode p = head, last_node = NULL;
        while(p){
            if(p -> next == NULL){
                existed.erase(p->page_id);
                if(last_node)
                    last_node -> next = NULL;
                else{
                    head = NULL;
                }
            }
            last_node = p;
            p = p -> next;
        }
    }
    
    void disp_page_in_memory(){
        cout<<"页面情况:"<<endl;
        PNode p = head;
        while(p){
            cout<<" "<<p->page_id;
            p = p -> next;
        }cout<<endl;
    }
    
    void call_page(int page_id){
        if(existed[page_id]){
            cout<<"In Memory"<<endl;
            update_order(page_id);
        }else{
            cout<<"Out of Memory"<<endl;
            if(existed.size() > blocks_limit){
                cout<<"页面置换"<<endl;
                delete_tail_page();
                insert_page(page_id);
            }else{
                cout<<"直接调页"<<endl;
                insert_page(page_id);
            }
        }
        disp_page_in_memory();
    }
    
private:
    PNode head;
    map<int, int>existed;
    int blocks_limit;
};

int main()
{
    LRU lru(3);
    while(1){
        int t;
        cin>>t;
        lru.call_page(t);
    }

    return 0;
}

最少使用次数(LFU)置换算法

先进先出置换算法(FIFO)

原文地址:https://www.cnblogs.com/luntai/p/6510228.html