📄 3_duan_distrib.cpp
字号:
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#define NULL 0
typedef struct table
{int address; /*存储分区起始地址*/
int length; /*存储分区长度*/
int flag; /*存储分区标志,0为空闲,1为被作业占据*/
char name[10]; /*存储分区占用标志作业名*/
struct table *next;
}node;
int success=0;/*分配成功与否的标志*/
node *work;
node *creat() /*定义函数,建立主存分配表*/
{ node *head;
node *p1,*p2;
int n=0;
printf("address length flag(0..1)\n");
p1=p2=(node *)malloc(sizeof(node));
scanf("%d%d%d",&p1->address,&p1->length,&p1->flag);
if(p1->flag==1&&p1->length>0)
{printf("\tinput job_name:");scanf("%s",p1->name);}
else strcpy(p1->name,"nil");
head=NULL;
while (p1->length!=0)
{n=n+1;
if (n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(node *) malloc (sizeof(node));
scanf("%d%d%d",&p1->address,&p1->length,&p1->flag);
if(p1->flag==1&&p1->length>0)
{printf("\t input job_name:");scanf("%s",p1->name);}
else strcpy(p1->name,"nil");
}
p2->next=NULL;
return(head);
}
node *found(node *head,int x) /*查找满足分配要求的最小空闲分区*/
{node *p,*q;
q=p=head;
while(p&&p->length<x)
p=p->next;
if(!p)
return(p);
else
{q=p;p=p->next;}
while(p)
{
if(q->length>p->length&&p->length>=x)
q=p;
p=p->next;
}
return(q);
}
node *distribute(node *head,node *work)
{node *q,*p,*pre;
q=pre=head;
p=found(head,work->length);
if(p)/*完成分配过程*/
{q=p;
success=1;work->address=q->address;work->flag=1;
if(q->length>work->length)/*剩余部分仍修改为空闲分区*/
{q->address=q->address+work->length;
q->length=q->length-work->length;}
else/*无剩余部分则删除该节点*/
if(q==head)
head=head->next;
else
{while(pre->next!=q)
pre=pre->next;
pre->next=q->next;
}
}
else
success=0;
return(head);
}
void print (node *head) /*输出链表*/
{ node *p;
p=head;
if(head !=NULL)
do{printf("%d,%d,%d,%s\n",p->address,p->length,p->flag,p->name);
p=p->next;}
while(p!=NULL);
}
void main()
{ int count,i,segment[64];
struct table *q,*q1,*q2,*p,*p1,*work;
char workname[10];
printf("The distributed table is:\n");
p=p1=creat(); /*输入已分配情况表*/
printf("the free table is:\n");
q=q1=q2=creat(); /*输入未分配情况表*/
printf("the work name is:");
scanf("%s",workname);
printf("input segment number:\n"); /*输入要分配的作业情况*/
scanf("%d",&count);
printf("input each segment length:\n"); /*输入每段的长度*/
for(i=0;i<count;i++)
{ scanf("%d",&segment[i]);
work=(node *)malloc(sizeof(node));
work->length=segment[i];work->next=NULL;
strcpy(work->name,workname);
q2=distribute(q1,work);
if (success)
{ while(p1->next)
p1=p1->next;
p1->next=work;
p1=work;
}
else
{ printf("\ndistributing is not successful!\n");
printf("\nfree table is !\n");
print(q);
printf("\ndistribute table is !\n");
print(p);
success=0;
break;
}
q1=q2;
}
if(success)
{printf("\ndistributing is successful!\n");
printf("\nfree table is !\n");
print(q);
printf("\ndistribute table is !\n");
print(p);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -