一个构成循环链表的空闲链表,每次分配都要找最佳分配的节点,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;
}