📄 duanzuoye2.cpp
字号:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5 //定义进程数
/*短作业优先算法*/
struct pro
{
int num; //进程名
int arrivetime; //到达时间
int burst; //运行时间;
struct pro *next;
};
//函数声明
struct pro* creatlist();
void insert(struct pro *head,struct pro *a);
struct pro* searchbySS(struct pro *head,int SS);
void run(struct pro *head);
void del(struct pro*b);
int getCount(struct pro* head,int time);
//创建链表,按照进程的到达时间排列
struct pro* creatlist()
{
struct pro* head=(struct pro*)malloc(sizeof(struct pro));
head->next=NULL;
struct pro* a;
int i;
for(i=0;i<MAX;i++)
{
a=(struct pro*)malloc(sizeof(struct pro));
printf("please enter the Process name:");
scanf("%d",&(a->num));
printf("please enter the arrivetime:");
scanf("%d",&(a->arrivetime));
printf("please enter the burst:");
scanf("%d",&(a->burst));
a->next=NULL;
insert(head,a);
}
return head;
}
//插入节点
void insert(struct pro *head,struct pro *a)
{
struct pro *b=searchbySS(head,a->arrivetime);
a->next=b->next;
b->next=a;
return;
}
//查找第一个到达时间大于等于SS的节点,返回其前一个指针
struct pro* searchbySS(struct pro *head,int SS)
{
struct pro *b,*c;
b=head;
c=head->next;
while(c!=NULL&&c->arrivetime<=SS)
{
b=c;
c=c->next;
}
return b;
}
//释放b的下一个节点
void del(struct pro* b)
{
struct pro *tmp;
tmp=b->next;
b->next=tmp->next;
free(tmp);
return;
}
//察看当前就绪队列中的进程数
int getCount(struct pro *head,int time)
{
int count=0;
struct pro *b,*c;
b=head;
c=b->next;
while(c!=NULL&&c->arrivetime<=time)
{
count++;
b=c;
c=c->next;
}
return count;
}
//选择运行时间最小的,返回其前一个节点的指针
struct pro* SJF(struct pro *head,int count)
{
int min;
struct pro *b,*c,*flag;
b=head;
c=b->next;
min=c->burst;
flag=b; //flag记录返回指针
while(count>0)
{
if(c->burst<min)
{
min=c->burst;
flag=b;
}
count--;
b=c;
c=c->next;
}
return flag;
}
//按短作业优先算法调度进程,并输出其运行情况
void run(struct pro *head)
{
int time=0,count;
struct pro *a,*d;
while(head->next!=NULL)
{
count=getCount(head,time);
if(count==0) //若当前就绪队列中没有进程,时间自增
time++;
else if(count==1) //若就绪队列中只有1个进程,则必定是第一个节点
{
d=head;
a=d->next;
printf("Process name:%d\n",a->num);
printf("arrivetime:%d\n",a->arrivetime);
printf("strat:%d\n",time);
printf("response time:%d\n",time-a->arrivetime);
time+=a->burst;
printf("the end:%d\n",time);
printf("Turn-around time:%d\n",time-a->arrivetime);
printf("\n");
del(d);
}
else //若就绪队列中的进程数>=2,则在head后的count个节点中进行短作业优先调度
{
d=SJF(head,count);
a=d->next;
printf("Process name:%d\n",a->num);
printf("arrivetime:%d\n",a->arrivetime);
printf("strat:%d\n",time);
printf("response time:%d\n",time-a->arrivetime);
time+=a->burst;
printf("the end:%d\n",time);
printf("Turn-around time:%d\n",time-a->arrivetime);
printf("\n");
del(d);
}
}
}
void main()
{
struct pro *head=creatlist();
printf("\n按短作业优先算法调度运行结果如下:\n");
run(head);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -