用c语言约瑟夫问题:有n个人围成一圈,顺序排号,从第一个开始报数(从1到m报数),凡报到m的人退出圈子,求最后剩下的是谁。编写一个程序,输入n(n<100),再输入n个整数,按上面描述的方法循环删除第3个数据(即m=3),输出最后剩下的那个整数。
时间: 2023-05-25 15:04:34 浏览: 202
```c
#include<stdio.h>
#include<stdlib.h>
struct node {
int num;
struct node *next;
};
struct node* createLinkedList(int n) {
struct node *head, *p, *q;
head = (struct node*)malloc(sizeof(struct node));
head->num = 1;
head->next = NULL;
p = head;
for (int i = 2; i <= n; i++) {
q = (struct node*)malloc(sizeof(struct node));
q->num = i;
q->next = NULL;
p->next = q;
p = q;
}
p->next = head; // 链表首尾连接成环形
return head;
}
int main() {
int n, m = 3;
struct node *head, *p, *pre;
scanf("%d", &n);
head = createLinkedList(n);
p = head;
while (p->next != p) { // 只剩下一个节点则退出循环
for (int i = 1; i < m; i++) {
pre = p;
p = p->next;
}
pre->next = p->next; // 删除p节点
printf("%d ", p->num);
free(p);
p = pre->next; // 从下一个节点开始报数,重新循环
}
printf("\n%d\n", p->num); // 输出最后剩下的节点
free(p);
return 0;
}
```
阅读全文
相关推荐
















