附录:约瑟夫环代码

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

typedef int data_t;

/* use a cycle linked list without header node */
typedef struct node_t
{
data_t data;
struct node_t *next;
} linknode_t, *linklist_t;

int main()
{
int i, n, m, k;
linklist_t p, q;
printf("total N people will join this suicide game, please input N:");
scanf("%d", &n);
printf( "people stand in a circle, assume everyone is assigned\n"
"a sequence number from 1 to %d.\n"\
"which one would you like to start the number off (1~%d):", n, n);
scanf("%d", &k);
printf("every Xth people should kill himself, please decide the X:");
scanf("%d", &m);

if (n < 1 || k > n || m < 1) {
printf("input error!\n");
return -1;
}

printf("game is starting ...\n");

/* added the first one */
p = q = (linklist_t)malloc(sizeof(linknode_t));
p->data = 1;

/* added other left people */
for (i = 2; i <= n; i++) {
q->next = (linklist_t)malloc(sizeof(linknode_t));
q = q->next;
q->data = i;
}
/* complete the circle */
q->next = p;
/* find the people ahead of #k */
q = p;
while (q->next != p) {
if (q->next->data == k)
break;
q = q->next;
}

while (q->next != q) { /* till the last one */

/* every m people */
for (i = 0; i < m - 1; i++)
{
q = q->next;
}

/* kill the m-th people */
p = q->next;
q->next = p->next;
printf("%-2d was killed\n", p->data);
free(p);
}

/* kill the last one */
printf("%-2d was alive\n", q->data);
free(q);

return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值