C语言关于链表的程序
1个回答
展开全部
前阵子做的用单向链表实现约瑟夫问题:
有M个人围一圈玩报数,凡报到N的出退出,输出每次退出的人的编号。
#include
"stdio.h"
struct
game
{
int
ID;
game
*pNext;
};
void
main()
{
int
i,m=17,n=3;
game
*pPrev,*pNode,*pTop;
printf("Input
M
N:");
scanf("%d
%d",&m,&n);
if(n>m||n<1)
return;
pTop=new
game;
pTop->ID=1;
pPrev=pTop;
for(i=2;i<=m;i++)
{
pNode=new
game;
pNode->ID=i;
pPrev->pNext=pNode;
pPrev=pNode;
}
pNode->pNext=pTop;
pPrev=pNode;
pNode=pTop;
i=0;
while(pNode->pNext!=pNode)
{
i++;
if(i%n==0)
{
printf("%d
",pNode->ID);
pPrev->pNext=pNode->pNext;
delete
pNode;
pNode=pPrev->pNext;
i=0;
}
else
{
pPrev=pNode;
pNode=pNode->pNext;
}
}
delete
pNode;
}
有M个人围一圈玩报数,凡报到N的出退出,输出每次退出的人的编号。
#include
"stdio.h"
struct
game
{
int
ID;
game
*pNext;
};
void
main()
{
int
i,m=17,n=3;
game
*pPrev,*pNode,*pTop;
printf("Input
M
N:");
scanf("%d
%d",&m,&n);
if(n>m||n<1)
return;
pTop=new
game;
pTop->ID=1;
pPrev=pTop;
for(i=2;i<=m;i++)
{
pNode=new
game;
pNode->ID=i;
pPrev->pNext=pNode;
pPrev=pNode;
}
pNode->pNext=pTop;
pPrev=pNode;
pNode=pTop;
i=0;
while(pNode->pNext!=pNode)
{
i++;
if(i%n==0)
{
printf("%d
",pNode->ID);
pPrev->pNext=pNode->pNext;
delete
pNode;
pNode=pPrev->pNext;
i=0;
}
else
{
pPrev=pNode;
pNode=pNode->pNext;
}
}
delete
pNode;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询