#include<stdio.h>
struct job{
int job_number;
int priority;
};
job priority_queue[100];
int length=0; //队列中的作业个数 全局变量
int allnumber=1; //作业号,依次递增,赋给增加的作业
int remove(){
if(length==0){
printf("There is no job!\n");
return 0;
}
int maxpriority=9999;
int number=9999;
int sign=0;
//遍历一次队列,找到最高优先级的作业
for(int i=0;i<length;i++){
if(priority_queue[i].priority<maxpriority){
maxpriority = priority_queue[i].priority;
number = priority_queue[i].job_number;
sign = i;
}
else if(priority_queue[i].priority==maxpriority)
if(priority_queue[i].job_number<number){
maxpriority = priority_queue[i].priority;
number = priority_queue[i].job_number;
sign = i;
}
}
printf("%d %d\n",priority_queue[sign].job_number,priority_queue[sign].priority);
//找到了作业,删除它
//从后往前依次覆盖
for(int i=sign;i<length-1;i++)
priority_queue[i] = priority_queue[i+1];
//作业个数减一
length--;
printf("Remove succeeds!\n");
return 1;
}
int add(){ //控制台输入一个优先级,系统自动赋予作业号
printf("Please input the priority: ");
int p; scanf("%d",&p);
//构成一个作业:作业号,优先级 并且加在队列最后
priority_queue[length] = {allnumber++,p};
//作业个数加一
length++;
printf("%d %d\n",priority_queue[length-1].job_number,priority_queue[length-1].priority);
printf("Add succeeds!\n");
return 1;
}
int list(){
printf("List:\n");
//一个for循环遍历整个数组
for(int i=0;i<length;i++)
printf("%d %d\n",priority_queue[i].job_number,priority_queue[i].priority);
printf("Over!\n");
return 1;
}
int menu(){
printf("Please input your operation:");
char operation;
scanf("%s",&operation);
switch (operation) {
case 'R':remove();break;
case 'A':add();break;
case 'L':list();break;
case '0':return 0;
default: printf("Illegal input.\n");
}
menu();
}
int main(){
menu();
return 1;
}
直接复制粘贴就能运行。
使用数组存储作业。每次出队时,先找到优先级最高的作业,然后删除它。