用C语言实现:设有n个人站成一排,从左向右的编号分别为1~n,现在从左往右报数“1,2,1,2,...”,数到“1”的人出列,数到“2”的立即站到队伍的最右端。报数过程反复进行,直到n个人都出列为止。要求给出他们的出列顺序。 例如,当n=8时,初始序列为 1 2 3 4 5 6 7 8 则出列顺序为 1 3 5 7 2 6 4 8
时间: 2024-03-16 20:45:25 浏览: 36
以下是用C语言实现该问题的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node *next;
} Node;
int main() {
int n, i, count = 0;
scanf("%d", &n);
Node *head, *tail, *p, *q;
head = tail = (Node*)malloc(sizeof(Node));
head->num = 1;
for (i = 2; i <= n; i++) {
p = (Node*)malloc(sizeof(Node));
p->num = i;
tail->next = p;
tail = p;
}
tail->next = head;
p = head;
while (p->next != p) {
count++;
if (count == 2) {
count = 0;
q->next = p->next;
free(p);
p = q->next;
} else {
q = p;
p = p->next;
}
}
printf("%d", p->num);
free(p);
return 0;
}
```
该程序使用循环链表来模拟人员的排队情况,每次数到1的节点出列,数到2的节点移到队列末尾。最终只剩下一个节点时,它就是最后一个出列的人员。