标签:style blog http io ar color sp for on
1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef struct node//一个进程的结构 4 { 5 int pid; //进程ID号 6 int priority; //进程优先数 7 int time; //进程分配的时间片 8 char state; //进程的状态 9 struct node * next; 10 }pcb; 11 12 13 pcb * p; 14 pcb * creat(); //进程的创建 15 int output(); //输出队列信息 16 pcb * insert(pcb * head,pcb * p); //进程p的插入 17 pcb * del(pcb * head,pcb * p); 18 int priority(pcb * head); 19 int s=0; 20 int a[10000]; 21 22 23 pcb * creat() //基于进程链表的创建 24 { 25 pcb * p1,* head; 26 int i,num; 27 head=NULL; 28 printf("进程个数:\n"); 29 scanf("%d",&num); 30 for(i=0;i<num;i++) 31 { 32 printf("请输入第%d个进程的信息:\n",i+1); 33 p1=(pcb *)malloc(sizeof(pcb)); 34 printf("输入进程优先数:\n"); 35 scanf("%d",&p1->priority); 36 printf("输入进程分配的时间:\n"); 37 scanf("%d",&p1->time); 38 p1->pid=i+1; 39 printf("\n"); 40 p1->state=‘W‘; 41 head=insert(head,p1); 42 } 43 return head; 44 } 45 46 int output(pcb * head) //输出链表信息 47 { 48 pcb * p; 49 p=head; 50 do 51 { 52 printf("%d %d %d %c\n",p->pid,p->priority,p->time,p->state); 53 p=p->next; 54 } 55 while(NULL!=p); 56 return 0; 57 } 58 59 pcb * insert(pcb * head,pcb * p) //将p按照优先级插入链表 60 { 61 pcb * p0,* p1,* p2; 62 p1=head; 63 p0=p; 64 if(head==NULL) 65 { 66 head=p0; 67 p0->next=NULL; 68 } 69 else 70 { 71 while((p1->priority>=p0->priority) && (p1->next!=NULL)) //寻找位置 72 { 73 p2=p1; 74 p1=p1->next; 75 } 76 if(p0->priority>p1->priority) //如果p0大于p1的优先级,找到存放的位置 77 { 78 if(head==p1) //并且p1正在运行,此时链表为p1,NULL 79 { 80 head=p0; 81 } 82 else 83 { 84 p2->next=p0; 85 p0->next=p1; 86 } 87 } 88 else //因为p1->next=NULL跳出 89 { 90 p1->next=p0; 91 p0->next=NULL; 92 } 93 } 94 return head; 95 } 96 97 pcb * del(pcb * head,pcb * p) //进程p的删除 98 { 99 p->state=‘F‘; 100 printf("进程%d已经DELETE\n",p->pid); 101 printf("\n"); 102 return head; 103 } 104 105 int priority(pcb * head) //进程的调度 106 { 107 char flag; 108 pcb * p,* rp; 109 p=head; 110 while(NULL!=p) 111 { 112 rp=p; 113 p=p->next; 114 do 115 { 116 flag=‘y‘; 117 printf("进程%drunning\n",rp->pid); 118 rp->state=‘R‘; 119 rp->priority=rp->priority-3; 120 rp->time--; 121 a[s++]=rp->pid; 122 output(rp); 123 rp->state=‘W‘; 124 printf("\n"); 125 if(0==rp->time) 126 p=del(p,rp); 127 else 128 { 129 if((p==NULL) || (rp->priority>=p->priority)) 130 flag=‘n‘; 131 else 132 { 133 p=insert(p,rp); 134 printf("当前链表信息\n"); 135 output(p); 136 printf("\n"); 137 } 138 } 139 } 140 while(flag==‘n‘); 141 } 142 return 0; 143 } 144 145 int main() 146 { 147 int i; 148 pcb * head=NULL; 149 printf("please input data!\n"); 150 head=creat(); 151 printf("链表信息\n"); 152 output(head); 153 printf("\n"); 154 printf("begin running!\n"); 155 printf("\n"); 156 priority(head); 157 for(i=0;i<s;i++) 158 { 159 printf("%d",a[i]); 160 if(i!=s-1) 161 printf("-->"); 162 } 163 printf("\n"); 164 return 0; 165 }
标签:style blog http io ar color sp for on
原文地址:http://www.cnblogs.com/Fchengli/p/4107569.html