用c语言实现约瑟夫环

2025-03-04 04:41:45
推荐回答(2个)
回答1:

正好之前写过基础的约瑟夫环,稍作修改就可以满足你的题目

#include 
#include 

typedef struct _node {
    int id;
    int key;
    struct _node *next;
} Linklist;

int main() {
int n, m;
scanf("%d %d", &n, &m);
int i, count = 0;
Linklist *head = (Linklist*)malloc(sizeof(Linklist)), *tail = head;
head->id = 1;
scanf("%d", &head->key);
head->next = head;
for(i = 2; i <= n; i++) {
Linklist *p = (Linklist*)malloc(sizeof(Linklist));
p->id = i;
scanf("%d", &p->key);
p->next = head;
tail->next = p;
tail = p;
}
while(head != tail) {
if(++count % m) {
tail = head;
} else {
    m = head->key;
    count = 0;
printf("%d ", head->id);
tail->next = head->next;
free(head);
}
head = tail->next;
}
printf("%d\n", head->id);
free(head);
return 0;
}

回答2:

这个问题有点意思,好玩!有空再来补上。