LRU简单实现C++

页面置换算法 在地址映射过程中,若在页面中发现所要访问的页面不再内存中,则产生缺页中断。当发生缺页中断时操作系统必须在内存选择一个页面将其移出内存,以便为即将调入的页面让出空间。而用来选择淘汰哪一页的规则叫做页面置换算法。下面是LRU简单实现:双向链表,时间复杂度O(n)
#include <iostream>
#include <assert.h>
using namespace std;

typedef struct node{
	int num; //页面编号
	node *next;	//
	node *pre;
}node;

typedef struct lru_queue{
	lru_queue(int n, int max){
		this->n=n;
		this->max=max;
		l=NULL;
	}
	
	int n;	//当前个数 
	int max; //最大内存容量
	node *l; 
}lru_queue;

void print(lru_queue q){
	node *p=q.l;
	while(p!=NULL){
		cout<<p->num<<"\t";
		p=p->next;
	}
	cout<<endl;
}
void print2(node *p){
	while(p!=NULL){
		cout<<p->num<<"\t";
		p=p->pre;
	}
	cout<<endl;
}

//lru队列l最大容量为max, 调入页面i, 返回调出页面 
int insert(lru_queue &q, int i){
	node *p=q.l;
	node *pre=NULL;
	while(p!=NULL && p->num!=i){
		pre=p;
		p=p->next;
	}
	
	int res=-1;
	if(p==NULL){
		if(q.n == q.max){
			pre->pre->next=NULL;
			res=pre->num;
			delete pre;
			
			node *tmp=new node;
			tmp->num=i;
			tmp->pre=NULL;
			tmp->next=q.l;
			
			q.l->pre=tmp;
			q.l=tmp;
		}else{
			node *tmp=new node;
			tmp->num=i;
			tmp->pre=NULL;
			tmp->next=q.l;
			
			if(q.l!=NULL)
				q.l->pre=tmp;
			q.l=tmp;
			q.n++;
		}
	}else{		
		if(p->pre!=NULL){
			p->pre->next=p->next;
		}
		if(p->next!=NULL){
			p->next->pre=p->pre;
		}
		delete p;
		
		node *tmp=new node;
		tmp->num=i;
		tmp->pre=NULL;
		tmp->next=q.l;
		
		q.l->pre=tmp;
		
		q.l=tmp;
	}
	return res;
}

int main(void){
	lru_queue q(0,3);
	print(q);

	assert(-1 == insert(q, 3));
	print(q);

	assert(-1 == insert(q, 5));
	print(q);

	assert(-1 == insert(q, 1));
	print(q);

	assert(-1 == insert(q, 5));
	print(q);

	assert(3 == insert(q, 4));
	print(q);	
	
	assert(-1 == insert(q, 1));
	print(q);
	
	system("pause");
	
	return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值