用C语言使用循环单链表实现约瑟夫环
时间: 2023-05-13 10:06:20 浏览: 169
好的,以下是用C语言使用循环单链表实现约瑟夫环的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n) {
Node *head = NULL, *tail = NULL;
for (int i = 1; i <= n; i++) {
Node *p = (Node *)malloc(sizeof(Node));
p->data = i;
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
tail->next = head;
return head;
}
void josephus(int n, int m) {
Node *head = createList(n);
Node *p = head, *prev = NULL;
while (p->next != p) {
for (int i = 1; i < m; i++) {
prev = p;
p = p->next;
}
prev->next = p->next;
printf("%d ", p->data);
free(p);
p = prev->next;
}
printf("%d\n", p->data);
free(p);
}
int main() {
int n, m;
printf("请输入总人数n和报数m:");
scanf("%d%d", &n, &m);
josephus(n, m);
return 0;
}
希望能对你有所帮助!
阅读全文
相关推荐
















