谁会C语言课程设计Josephus问题 15
有一群学生围成一圈,顺序编号,从第一个学生起,顺时针方向报数,从1报到m,凡是报到m的学生离开圈子,随着学生的不断离开,圈子越缩越小,最后剩下的学生便是胜利者,问最后剩下...
有一群学生围成一圈,顺序编号,从第一个学生起,顺时针方向报数,从1报到m,凡是报到m的学生离开圈子,随着学生的不断离开,圈子越缩越小,最后剩下的学生便是 胜利者,问最后剩下的学生是原来的第几号? 分析:首先对每一个学生赋以一个序号值作为学生离开时,将他的序号改为0作为离开的标志。
展开
2个回答
展开全部
#include <stdio.h>
#include <malloc.h>
struct Link{
int id;
Link *next;
};
void Initialize(int n, Link *head)
{
int i;
Link *p;
for (i = 1, p = head; i <= n; i++){
p-> next = (Link *) malloc (sizeof(Link));
p = p-> next;
p-> id = i;
}
p-> next = head-> next;
}
void Delete(Link *node)
{
Link *temp;
temp = node-> next;
printf( "%d ", node-> next-> id);
node-> next = temp-> next;
free(temp);
}
void main()
{
Link *head, *p;
int n, i, k;
printf( "%s ", "Input n,k = ");
scanf( "%d%d ", &n, &k);
head = (Link *) malloc (sizeof(Link));
head-> next = (Link *) malloc (sizeof(Link));
Initialize(n, head);
for (p = head, i = 1; p != p-> next; p = p-> next, i++){
if (i == k){
i = 1;
Delete(p);
}
}
printf( "\n ");
printf( "%d ", p-> id);
}
#include <malloc.h>
struct Link{
int id;
Link *next;
};
void Initialize(int n, Link *head)
{
int i;
Link *p;
for (i = 1, p = head; i <= n; i++){
p-> next = (Link *) malloc (sizeof(Link));
p = p-> next;
p-> id = i;
}
p-> next = head-> next;
}
void Delete(Link *node)
{
Link *temp;
temp = node-> next;
printf( "%d ", node-> next-> id);
node-> next = temp-> next;
free(temp);
}
void main()
{
Link *head, *p;
int n, i, k;
printf( "%s ", "Input n,k = ");
scanf( "%d%d ", &n, &k);
head = (Link *) malloc (sizeof(Link));
head-> next = (Link *) malloc (sizeof(Link));
Initialize(n, head);
for (p = head, i = 1; p != p-> next; p = p-> next, i++){
if (i == k){
i = 1;
Delete(p);
}
}
printf( "\n ");
printf( "%d ", p-> id);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询