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;
}

猜你喜欢

转载自chuanwang66.iteye.com/blog/1959817