《首次适应算法和最佳适应算法-C++语言版》由会员分享,可在线阅读,更多相关《首次适应算法和最佳适应算法-C++语言版(6页珍藏版)》请在金锄头文库上搜索。
1、#include #include using namespace std; #define Free 0 /空闲状态 #define Busy 1 /已用状态 #define OK 1 /完成 #define ERROR 0 /出错 #define MAX_length 512 /最大内存空间为 512KB typedef int Status; int flag;typedef struct freearea/定义一个空闲区说明表结构 long size; /分区大小long address; /分区地址int state; /状态 ElemType;/ 线性表的双向链表存储结构 type
2、def struct DuLNode ElemType data;struct DuLNode *prior; /前趋指针struct DuLNode *next; /后继指针 DuLNode,*DuLinkList; DuLinkList block_first; /头结点 DuLinkList block_last; /尾结点 Status alloc(int);/内存分配 Status free(int); /内存回收 Status First_fit(int);/首次适应算法 Status Best_fit(int); /最佳适应算法 void show();/查看分配 Status
3、Initblock();/开创空间表Status Initblock()/开创带头结点的内存空间链表 block_first=(DuLinkList)malloc(sizeof(DuLNode);block_last=(DuLinkList)malloc(sizeof(DuLNode);block_first-prior=NULL;block_first-next=block_last;block_last-prior=block_first;block_last-next=NULL;block_last-data.address=0;block_last-data.size=MAX_leng
4、th;block_last-data.state=Free;return OK; /分配主存 Status alloc(int ch) int request = 0;coutrequest;if(requestdata.size=request;temp-data.state=Busy;DuLNode *p=block_first-next;while(p)if(p-data.state=Free return OK;break;if(p-data.state=Free temp-next=p;temp-data.address=p-data.address;p-prior-next=tem
5、p;p-prior=temp;p-data.address=temp-data.address+temp-data.size;p-data.size-=request;return OK;break;p=p-next;return ERROR; /最佳适应算法 Status Best_fit(int request) int ch; /记录最小剩余空间DuLinkList temp=(DuLinkList)malloc(sizeof(DuLNode);temp-data.size=request;temp-data.state=Busy;DuLNode *p=block_first-next;
6、DuLNode *q=NULL; /记录最佳插入位置while(p) /初始化最小空间和最佳位置if(p-data.state=Free ch=p-data.size-request; else if(q-data.size p-data.size) q=p;ch=p-data.size-request; p=p-next;if(q=NULL) return ERROR;/没有找到空闲块else if(q-data.size=request)q-data.state=Busy;return OK; else temp-prior=q-prior;temp-next=q;temp-data.ad
7、dress=q-data.address;q-prior-next=temp;q-prior=temp;q-data.address+=request;q-data.size=ch;return OK; return OK; /主存回收 Status free(int flag) DuLNode *p=block_first; for(int i= 0; i next; else return ERROR;p-data.state=Free;if(p-prior!=block_first p-prior-next=p-next;p-next-prior=p-prior; p=p-prior;i
8、f(p-next!=block_last p-next-next-prior=p;p-next=p-next-next; if(p-next=block_last p-next=NULL;return OK; /显示主存分配情况 void show() int flag = 0;coutnext; coutdata.addressdata.sizedata.state=Free) coutnext;coutch; while(ch2) coutch; Initblock(); /开创空间表int choice; /操作选择标记while(1) show(); coutchoice;if(choice=1) alloc(ch); / 申请内存else if(choice=2) / 释放回收int flag;coutflag;free(flag);else if(choice=0) break; /退出else /输入操作有误cout“输入有误,请重试!“endl;continue;