NF算法:
分两个区,一个空闲区,一个申请区。
逻辑:
申请区的下一块是申请区上一块在空闲区结束的位置开始查找。说白了双循环就是了
代码区:
#include<iostream>
#include<list>
using namespace std;
struct LCapacityNode
{
int startAddress;
int size;
int endAddress;
string state;
};
list<LCapacityNode>capacityNode;
list<LCapacityNode>needCapacityNode;
void showData(list<LCapacityNode>& l) {
cout << "起始地址\t" << "容量大小\t" << "尾地址\t" << "\t状态" << endl;
for (list<LCapacityNode>::iterator it = l.begin(); it != l.end(); it++) {
cout << it->startAddress << "\t\t" << it->size << "\t\t" << it->endAddress << "\t\t" << it->state << endl;
}
}
void InitListCapacity() {
LCapacityNode L1 = { 0,1023,L1.startAddress + L1.size,"空闲区" };
LCapacityNode L2 = { L1.startAddress + L1.size + 1,2047,L2.startAddress + L2.size,"空闲区" };
LCapacityNode L3 = { L2.startAddress + L2.size + 1,3071,L3.startAddress + L3.size,"空闲区" };
LCapacityNode L4 = { L3.startAddress + L3.size + 1,4095,L4.startAddress + L4.size,"空闲区" };
LCapacityNode L5 = { L4.startAddress + L4.size + 1,5119,L5.startAddress + L5.size,"空闲区" };
LCapacityNode L6 = { L5.startAddress + L5.size + 1,6143,L6.startAddress + L6.size,"空闲区" };
capacityNode.push_back(L1);
capacityNode.push_back(L2);
capacityNode.push_back(L3);
capacityNode.push_back(L4);
capacityNode.push_back(L5);
cout << "----------------------初始空闲区----------------------" << endl;
showData(capacityNode);
cout << "------------------------------------------------------" << endl;
}
void InitNeedCapacityNode() {
cout << "请输入要申请的节点个数:";
int sum;
cin >> sum;
LCapacityNode L;
for (int i = 1; i <= sum; i++) {
//只需要输入申请容量即可
L.startAddress = 0;
L.endAddress = 0;
cout << "请输入第" << i << "个节点的所需容量:";
cin >> L.size;
L.state = "未分配";
needCapacityNode.push_back(L);
}
cout << "----------------------初始申请区----------------------" << endl;
showData(needCapacityNode);
cout << "------------------------------------------------------" << endl;
}
void FFAlgorithm() {
for (list<LCapacityNode>::iterator it = capacityNode.begin(); it != capacityNode.end(); it++) {
for (list<LCapacityNode>::iterator jt = needCapacityNode.begin(); jt != needCapacityNode.end(); jt++) {
//如果有满足的数据
if ((it->size >= jt->size) && (jt->state == "未分配")) {
//把首地址给到需要分配的
jt->startAddress = it->startAddress;
//目标地址的尾地址
jt->endAddress = jt->startAddress + jt->size;
//更新区域的首地址
it->startAddress += jt->size + 1;
//把当前地址的容量减少
it->size -= jt->size;
//改变状态
jt->state = "已分配";
}
}
}
cout << "----------------------所剩空闲区----------------------" << endl;
showData(capacityNode);
cout << "------------------------------------------------------" << endl;
cout << "---------------------NF算法完成区---------------------" << endl;
showData(needCapacityNode);
cout << "------------------------------------------------------" << endl;
}
int main() {
InitListCapacity();
InitNeedCapacityNode();
FFAlgorithm();
return 0;
}