標(biāo)題: C語(yǔ)言:約瑟夫環(huán)問題(源代碼) [打印本頁(yè)]

作者: geige    時(shí)間: 2015-7-26 00:46
標(biāo)題: C語(yǔ)言:約瑟夫環(huán)問題(源代碼)
本帖最后由 geige 于 2015-7-26 00:48 編輯


#include<stdio.h>
#include<stdlib.h>

struct stu //構(gòu)建一個(gè)新的數(shù)據(jù)類型
{
int num;

struct stu *next;

};

struct stu *createlist(int n);  //函數(shù)聲明
int main()
{
struct stu *head,*p,*temp;   //定義頭指針,以及中間指針temp,用來(lái)刪除節(jié)點(diǎn)

int n,m,i,j=1,flag=0;

printf("Please input n and m:\n");
scanf("%d%d",&n,&m);

head=createlist(n);          //調(diào)用函數(shù)來(lái)創(chuàng)建鏈表并返回頭指針賦值給head


p=head->next;                //將首節(jié)點(diǎn)的地址賦值給p

if(m==1)                     //如果m等于1,直接按順序輸出
{
while(p!=NULL)
{
printf("%d ",p->num);
p=p->next;
}

putchar('\n');
}

else
{

while(n!=1)
{
for(i=1;i<=n;i++)
{
if(p!=NULL)
{
if(j==m)
{
printf("%d ",p->num);

if(p==head->next)
head->next=p->next; //如果刪除的是首結(jié)點(diǎn),那么將第二個(gè)節(jié)點(diǎn)作為首節(jié)點(diǎn)
temp->next=p->next;
p=temp->next;
j=1;
flag++;
}
else
{
j++;
temp=p;
p=p->next;
}
}
}

n=n-flag; //退出的人數(shù)要減去
flag=0;
p=head->next; //將首節(jié)點(diǎn)重新賦給p
}

printf("%d\n",temp->num); //輸出最后一個(gè)數(shù)
}

free(p); //釋放內(nèi)存

    return 0;

}


struct stu *createlist(int n)
{
int i;

struct stu *phead=(struct stu*)malloc(sizeof(struct stu)),*ptail;  //申請(qǐng)頭結(jié)點(diǎn)

if(phead==NULL)
{
printf("Not able apply for memory !\n");

return 0;
}

ptail=phead; //
ptail->next=NULL; //將頭結(jié)點(diǎn)的下一個(gè)地址置空

for(i=1;i<=n;i++)
{
struct stu *pnew=(struct stu*)malloc(sizeof(struct stu)); //開辟新的節(jié)點(diǎn)

if(pnew==NULL)
{
printf("Not able apply for memory !\n");

return 0;
}

pnew->num=i;
ptail->next=pnew;
pnew->next=NULL;
ptail=pnew; //節(jié)點(diǎn)前移
}
return phead; //返回頭指針


}







歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1