哲學(xué)家就餐問題C原代碼

字號:

題目:
    一群哲學(xué)家圍坐在一個圓桌,手上持有密碼m,并從1開始編了號取初值m,哲學(xué)家從1開始報數(shù), 報到m的哲學(xué)家停止吃飯,退出圓桌,求哲學(xué)家退出的順序。要求:n和初值m由完家輸入.手上的密碼隨機(jī)產(chǎn)生.最后要打印出編號對應(yīng)的密碼,輸出哲學(xué)家離開的相后順序
    分析:可用循環(huán)鏈表實現(xiàn),鏈表數(shù)據(jù)類型為結(jié)構(gòu)體,記錄編號和相應(yīng)密碼,另外設(shè)標(biāo)志哲學(xué)家報數(shù)的變量mouth, 它的值和哲學(xué)家嘴上報的數(shù)相等,則如果mouth和m相等,該哲學(xué)家就應(yīng)該離開離開前取他的密碼交給m,同時將他的編號放另一單鏈表numbsave保存。注意編號要從numbsave的最后節(jié)點插入。當(dāng)循環(huán)鏈表指向自身時停止比較,這個哲學(xué)家即是最后離開的一個.依次打印出numbsave中的數(shù)即為按編號哲學(xué)家離開的先后順序。
    */
    #include "stdio.h"
    #include "conio.h"
    #include "stdlib.h"
    struct philosopher /*哲學(xué)家就餐結(jié)構(gòu)體*/
    { int number; /*編號*/
    int password;
    int mouth; /*嘴上報的數(shù)*/
    struct philosopher *next;
    };
    struct philosopher *phead,*pend,*pp;
    struct numbsave /*存放離開順序*/
    { int numsave;
    struct numbsave *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("please input n m:");
    scanf("%d%d",&n,&m); /*n為哲學(xué)家人數(shù),m為初始密碼*/
    phead=(struct philosopher *)malloc(sizeof(struct philosopher));
    pend=phead;phead->mouth=1;
    for(b=1;b<=n-1;b++) /*給哲學(xué)家分配隨機(jī)密碼*/
    {pend->number=b;
    k=random(20); /*k為0
    while(k<=0)
    k=random(20);
    pend->password=k;
    pp=(struct philosopher *)malloc(sizeof(struct philosopher));
    pend->next=pp; pend=pp;
    }