哲学家就餐问题,第1张

哲学家就餐问题,第2张

/*题目:一群哲学家围坐在一张圆桌旁,手里拿着密码M,从1开始数,得到初始值M,哲学家从1开始数,向M汇报的哲学家停止吃饭,退出圆桌。找出哲学家退出的顺序。要求:N和初始值M由族末输入。手里的密码是随机生成的。最后要打印出数字对应的密码,输出哲学家出发的顺序。

解析:可以用循环链表实现。链表的数据类型是结构、记录号和对应的密码。此外,还设置了一个名为mouth的变量,用来标记哲学家报告的数字。如果mouth和M相等,哲学家在离开前要把他的密码拿到M,把他的号码放到另一个单链表numbsave中保存。注意,应该从numbsave的最后一个节点插入数字。当循环链表指向自身时,比较停止,这个哲学家是最后一个离开的。依次打印出numbsave中的数字,就是哲学家按数字离开的顺序。

*/

# include " stdio . h "
# include " conio . h "[br/]# include " stdlib . h "

Struct哲学家/*哲学家用餐结构*/
{ int number;/* number */
int密码;
int口;/*口报数*/
struct哲学家*下一个;
};
结构哲学家*phead,*pend,* pp

Struct numbsave /*存款和离开订单*/
{ int nums save;
struct numb save * next;
};
struct numbsave *top=NULL,*numbnew,* numbthis

void main(void)
{ char *p,d;
int b=1,k,n,m,mouthm = 1;
clrscr();gotoxy(9,8);
printf("请输入n m:");
scanf("%d%d ",&n,& m);/*n是哲学家的数量,m是初始密码*/
phead =(struct philosopher *)malloc(sizeof(struct philosopher));
pend = phead;phead-> mouth = 1;
for(b = 1;b { pend-> number = b;
k = random(20);/*k是0next = pppend = pp
}
pend-> number = b;/*最后的哲学家*/
k = random(20);while(k password = k;pend-> next = phead;/*形成一个循环链表*/
printf(" \ n \ tphilospher数字对应password如下:\ n \ t ");
PP = phead;
for(b = 1;b编号,pp->密码);
PP = PP-> next;
}

while(挂起->下一个!= pend)
{ If(phead-> mouth = = m)/*如果口报数等于m,则表示一个人要走*/
{ PP = phead;
phead-> next-> mouth = 1;mouthm = 1;/*下一位哲人从头开始报告,mm用来把顺序报告的数字给嘴*/
phead = pend-> next = phead-> next;/*两个指针必须相邻*/
numbnew =(structnumbserve *)malloc(sizeof(structnumbserve));
m=pp->密码;/*修改m的值离开哲学家的密码*/
numbnew-> numsave = PP-> number;
if(top = = NULL){ top = numb new;top-> next = NULL;}/*离去哲学家的编号存储在numbsave */
else的最后一个节点中{ numbthis = top
while(numbthis->next!= NULL)numb this = numb this-> next;
numb this--> next = numb new;numb new-> next = NULL;
}
免费(PP);
}
else { pend = pend-> next;
phead = phead-> next;/*让phead指向下一个*/
mouth m++;
phead-> mouth = mouthm;/*我的嘴巴说我应该向mouthm报告*/
}
} /* Print离开餐桌的顺序*/
printf(" \ n \ tphilospher在下面的队列中离开烹饪台:\ n \ t ");
while(顶!=NULL)
{ printf("%d ",top-> numsave);
top = top-> next;
}
printf("%d ",pend-> number);/*别忘了,他是个幸运儿*/
printf(" \ n \ t按任意键返回...");
while(!kb hit());
}

位律师回复
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » 哲学家就餐问题

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情