用c语言链表实现猴子选大王的程序
时间: 2023-05-20 11:04:28 浏览: 102
C语言实现猴子选大王程序
非常感谢您的提问!以下是用 C 语言链表实现猴子选大王的程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node *next;
} Node;
int main() {
int n, m;
printf("请输入猴子的数量和报数的数字:\n");
scanf("%d %d", &n, &m);
Node *head = NULL, *tail = NULL;
for (int i = 1; i <= n; i++) {
Node *new_node = (Node *) malloc(sizeof(Node));
new_node->num = i;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
}
tail->next = head;
Node *p = head, *prev = tail;
int count = 0;
while (p->next != p) {
count++;
if (count == m) {
printf("%d ", p->num);
prev->next = p->next;
free(p);
p = prev->next;
count = 0;
} else {
prev = p;
p = p->next;
}
}
printf("%d\n", p->num);
return 0;
}
```
希望这个程序能够帮助到您!
阅读全文