约瑟夫环问题单链表c++
时间: 2023-11-24 08:46:13 浏览: 92
可以使用单向循环链表来解决约瑟夫环问题。具体实现方法是:先构建一个有n个结点的单向循环链表,然后从头结点开始,每次数m个结点,将数到的第m个结点删除,直到链表中只剩下一个结点为止。
代码实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n) {
Node *head = NULL, *p = NULL, *tail = NULL;
int i;
for (i = 1; i <= n; i++) {
p = (Node*)malloc(sizeof(Node));
p->data = i;
if (tail == 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, *pre = NULL;
int i, count = 0;
while (p->next != p) {
count++;
if (count == m) {
printf("%d ", p->data);
pre->next = p->next;
free(p);
p = pre->next;
count = 0;
} else {
pre = p;
p = p->next;
}
}
printf("%d\n", p->data);
}
int main() {
int n, m;
printf("Enter n and m: ");
scanf("%d%d", &n, &m);
josephus(n, m);
return 0;
}
```
阅读全文