空闲链表,循环链表,找最合适的节点

一个构成循环链表的空闲链表,每次分配都要找最佳分配的节点,n次分配之后,输出链表的最后状态。

思路:

1、结构体存储空闲块的起始位置、大小,这个循环链表用数组表示(没必要用指针,数组存储就行了,指针难操作,如果把哪个空闲块全分配完了,直接将数组中该项全部置0就行,而且数组天然就有了顺序,要打造循环链表的效果,只需要两个for循环,一个从now到结尾,一个从0到now)

2、每次分配后注意更新当前位置now,正好全分配完一个节点的话就将now指向下一个节点(注意这是指向的是下一个能分配的节点,体现在数组中就是空间不为0的节点),不是正好分配完的话当前位置还是当前位置。

3、寻找最佳位置的时候,先全部遍历一遍看是不是有正好合适的,没有的话再找在满足要切且空闲区最小的分配。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<sstream>
#include<set>
#include<queue>
using namespace std;
struct node{
	int address;
	int space;
}nlist[110];
int request[105]={0};
int now=0,best_index=0,best_space;
int n,m;
void find_best(int x){
	int i=0;
	for(i=now;i<n;i++){
		if(nlist[i].space==x){
			nlist[i].space=0;
			for (int j = i + 1; j < n; j++) {
				if (nlist[j].space != 0) {
					now=j%n;
					return;
				}
			}
			for (int j = 0; j < i; j++) {
				if (nlist[j].space != 0) {
					now = j % n;
					return;
				}
			}
		}
	}
	for(i=0;i<now;i++){
		if(nlist[i].space==x){
			nlist[i].space=0;
			for (int j = i + 1; j < n; j++) {
				if (nlist[j].space != 0) {
					now = j % n;
					return;
				}
			}
			for (int j = 0; j < i; j++) {
				if (nlist[j].space != 0) {
					now = j % n;
					return;
				}
			}
			return;
		}
	}
	best_index=now;
	best_space=1000000;
	for(i=now;i<n;i++){
		if(nlist[i].space>x&&nlist[i].space<best_space){
			best_index=i;
			best_space=nlist[i].space;
		}
	}
	for(i=0;i<now;i++){
		if(nlist[i].space>x&&nlist[i].space<best_space){
			best_index=i;
			best_space=nlist[i].space;
		}
	}
	if(best_space!=1000000){
		nlist[best_index].space=nlist[best_index].space-x;
		now=best_index;
		return;
	}
	return;
}

int main() {
	cin>>n;
	int i=0;
	for(i=0;i<n;i++){
		cin>>nlist[i].address>>nlist[i].space;
	}
	for(i=0;i<110;i++){
		cin>>request[i];
		if(request[i]==-1){
			break;
		}
	}
	m=i;//表示共多少个请求
	for(i=0;i<m;i++){
		find_best(request[i]);
	}
	for(i=now;i<n;i++){
		if(nlist[i].space!=0){
			cout<<nlist[i].address<<" "<<nlist[i].space<<endl;
		}
	}
	for(i=0;i<now;i++){
		if(nlist[i].space!=0){
			cout<<nlist[i].address<<" "<<nlist[i].space<<endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值