#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include "iostream"
#define getpch(type) (type *)malloc(sizeof(type))
#define NULL 0

struct PCB  //定义进程控制块
{
	char name[10];
	char state;
	int super;
	int ntime;
	int rtime;//已经运行的时间
	struct PCB* link;
}*ready = NULL, * p;

void sort()//对进程进行优先级排列
{
	PCB* first, * second;
	int insert = 0;
	if ((ready == NULL) || ((p->super) > (ready->super)))  //优先级最大者插入队首
	{
		p->link = ready;
		ready = p;
	}
	else     // 进程比较优先级 ,插入适当位置中
	{
		first = ready;
		second = first->link;
		while (second != NULL)
		{
			if ((p->super) > (second->super)) //若插入进程比当前进程优先数大 插入到当前进程前面
			{
				p->link = second;
				first->link = p;
				second = NULL;
				insert = 1;
			}
			else   //插入进程优先数最低 则插入到队尾
			{
				first = first->link;
				second = second->link;
			}
		}
		if (insert == 0)
			first->link = p;
	}
}
//对sort函数的注释:
//
//
void input()   //建立进程控制快
{
	int i, num;
	system("cls");
	printf("\n 请输入进程个数");
	scanf("%d", &num);
	for (i = 0; i < num; i++)
	{
		printf("\n 进程号 No.%d:\n", i);
		p = getpch(PCB);
		printf("\n输入进程名:");
		scanf("%s", p->name);
		printf("\n输入进程优先数:");
		scanf("%d", &p->super);
		printf("\n输入进程运行时间:");
		scanf("%d", &p->ntime);
		printf("\n");
		p->rtime = 0;
		p->state = 'w';
		p->link = NULL;
		sort();
	}
}

int space()
{
	int l = 0;
	PCB* pr = ready;
	while (pr != NULL)
	{
		l++;
		pr = pr->link;
	}
	return(1);
}

void disp(PCB* pr)   //显示当前进程
{
	printf("\n qname\t state \t super \t ndtime \t runtime\n");
	printf("|%s\t", pr->name);
	printf("|%c\t", pr->state);
	printf("|%d\t", pr->super);
	printf("|%d\t", pr->ntime);
	printf("|%d\t", pr->rtime);
	printf("\n");
}

void check()    //进程查看函数
{
	PCB* pr;
	printf("\n***当前正在运行的进程是:%s", p->name);
	disp(p);
	pr = ready;
	printf("\n***当前就绪状态队列为:\n");
	while (pr != NULL)
	{
		disp(pr);
		pr = pr->link;
	}
}

void  destroy()
{
	printf("\n进程[%s]已经完成\n", p->name);
	free(p);
}

void running()  //进程就绪函数
{
	(p->rtime)++;
	if (p->rtime == p->ntime)
		destroy();
	else
	{
		(p->super)--;
		p->state = 'w';
		sort();
	}
}

void main()
{
	int len, h = 0;
	char ch;
	input();
	len = space();
	while ((len != 0) && (ready != NULL))
	{
		ch = getchar();
		h++;
		printf("\n The execute number:%d\n", h);
		p = ready;
		ready = p->link;
		p->link = NULL;
		p->state = 'R';
		check();
		running();
		printf("\n按任意键继续.....");
		ch = getchar();
	}
	printf("\n\n进程已经完成\n");
	ch = getchar();
}