(C语言)猴子选大王链式结构
时间: 2023-06-22 07:41:21 浏览: 129
好的,下面是链式结构的猴子选大王的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct monkey {
int num;
struct monkey *next;
} Monkey;
Monkey *createMonkeyList(int n) {
Monkey *head = NULL, *p, *tail;
int i;
for (i = 1; i <= n; i++) {
p = (Monkey*)malloc(sizeof(Monkey));
p->num = i;
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
}
tail->next = head; // 链表首尾相连
return head;
}
int monkeyKing(Monkey *head, int m) {
Monkey *p = head, *q;
int i;
while (p->next != p) {
for (i = 1; i < m; i++) {
q = p;
p = p->next;
}
q->next = p->next;
printf("%d ", p->num);
free(p);
p = q->next;
}
return p->num;
}
int main() {
int n, m;
printf("请输入猴子数量和报数上限:");
scanf("%d%d", &n, &m);
Monkey *head = createMonkeyList(n);
printf("出圈的顺序为:");
int king = monkeyKing(head, m);
printf("\n大王的编号为:%d\n", king);
return 0;
}
```
代码思路:
首先创建一个包含n个猴子的链表,然后将链表首尾相连,形成一个环。接着模拟猴子选大王的过程,每次从当前位置开始报数,报到第m只猴子时,将该猴子从链表中删除并打印出来。最后剩下的猴子即为大王。
阅读全文