使用c语言,创建单向循环列表实现约瑟夫环,并分成头文件和源文件以及主函数
时间: 2024-05-03 17:21:55 浏览: 71
约瑟夫环问题通过循环链表实现(c语言版)
头文件:josephus.h
```c
#ifndef JOSEPHUS_H
#define JOSEPHUS_H
typedef struct node {
int data;
struct node *next;
} Node;
Node* createList(int n);
void josephus(int n, int m);
#endif
```
源文件:josephus.c
```c
#include "josephus.h"
#include <stdio.h>
#include <stdlib.h>
Node* createList(int n) {
Node *head = NULL, *prev = NULL, *curr = NULL;
for (int i = 1; i <= n; i++) {
curr = (Node*)malloc(sizeof(Node));
curr->data = i;
if (head == NULL) {
head = curr;
} else {
prev->next = curr;
}
prev = curr;
}
curr->next = head;
return head;
}
void josephus(int n, int m) {
Node *head = createList(n);
Node *prev = head, *curr = head->next;
while (n > 1) {
for (int i = 1; i < m; i++) {
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
free(curr);
curr = prev->next;
n--;
}
printf("The last one is: %d\n", prev->data);
}
```
主函数:main.c
```c
#include "josephus.h"
int main() {
int n = 10, m = 3;
josephus(n, m);
return 0;
}
```
阅读全文