#include<stdio.h>
#include<stdlib.h>
void main() {
int n, c,num=0,i=0,pos=-1;
scanf("%d %d", &n, &c);
int *a;
a = (int *)malloc(sizeof(int) * n);
for (int i = 0;i < n;i++)
a[i]=0;
while (num < n) {
while (i<c) {
pos = (pos + 1) % n;
if(a[pos]==0)
i++;
}
if (i== c) {
i = 0;
a[pos] = 1;
printf("%d ", pos+1);
num++;
}
}
}
用链表实现
//约瑟夫环(用链表实现)
typedef struct node {
int data;
node *next;
}*Linklist, node;
#include<stdio.h>
#include<stdlib.h>
void main() {
node* rear, *p, *head, *pre;
int n, m;
printf("请输入人数:");
scanf("%d", &n);
head = (node*)malloc(sizeof(node));
head->next = NULL;
rear = head;
for (int i = 1;i <= n;i++) {//初始化链表赋值1 2 3 4 。。。
p = (node*)malloc(sizeof(node));
p->data = i;
p->next = NULL;
rear->next = p;
rear = p;
}
p = head;
printf("请输入报数m:");
scanf("%d", &m);
while (p) {
for (int i = 0;i < m;i++) {//数m个数
if (p == NULL)
break;
if (p == rear) {
pre = head;
p = head->next;
}
else {
pre = p;
p = p->next;
}
}//for
if (p != NULL) {
printf("%d ", p->data);
if (p == rear) {//p为尾结点
if (rear == head->next)//p为链表中最后一个结点,程序结束
return;
pre->next = NULL;//p为尾结点,且p前面还有结点
free(p);
p = pre;rear = pre;
}
else {//p不为尾结点,位于链表中间,删除p
pre->next = p->next;
free(p);
p = pre;
}//if
}//if
}//while
}