计算理工学院有 NN 个同学,围成了一个圆圈,每人被顺序地编了一个序号(分别为 1,2,3... n1,2,3...n),从编号为 KK 的人开始报 11,他之后(顺初始数字增长方向计算序号)的人报 22,以此类推,数到某一个数字 MM 的人出列。出列同学的下一个人又从 11 开始继续报数,数到某一个数字 MM 的人出列。不断重复这一过程,直到所有人都出列为止。
你需要根据同学人数 NN 和给出的 KK 和 MM 计算出同学的正确出列顺序。
这一题的main
函数已经帮你写好了,同时,已经帮你定义了一个节点的结构体类型、通过circle_create
创建了一个循环链表。
现在请在count_off
函数中根据传入的编号为 11 的节点 headhea**d、学生数 nn、起始报数学生编号 kk、数到出列的数字 mm 实现报数的过程,按照题目要求进行输出。
测评机会反复运行你的程序。每次程序运行时,输入为一行,包括三个被空格分隔开的符合描述的正整数 N、K和 M(1≤K≤N≤1000,1 <= M <= 2000)。
输出为一行,包含 N 个整数,为依次顺序出列的学生编号,由空格分隔开。
9 1 1
xxxxxxxxxx
1 2 3 4 5 6 7 8 9
xxxxxxxxxx
8 5 2
xxxxxxxxxx
6 8 2 4 7 3 1 5
x
typedef struct node {
int data;
struct node *next;
} Node;
Node *circle_create(int n);
void count_off(Node *head, int n, int k, int m);
int main() {
int n, k, m;
scanf("%d%d%d", &n, &k, &m);
Node *head = circle_create(n);
count_off(head, n, k, m);
return 0;
}
Node *circle_create(int n) {
Node *temp, *new_node, *head;
int i;
// 创建第一个链表节点并加数据
temp = (Node *) malloc(sizeof(Node));
head = temp;
head->data = 1;
// 创建第 2 到第 n 个链表节点并加数据
for(i = 2; i <= n; i++) {
new_node = (Node *) malloc(sizeof(Node));
new_node->data = i;
temp->next = new_node;
temp = new_node;
}
// 最后一个节点指向头部构成循环链表
temp->next = head;
return head;
}
void count_off(Node *head, int n, int k, int m) {
Node *temp = head;
int t = 1; // 使指针指到开始报号的学生编号
while (t != k) {
temp = temp -> next;
++t;
}
int a = 1;
t = n;
while (n) {
// 如果指针指到了最后一个学生,重新指向第一个学生
if (temp->data) {
if (a == m) {
printf("%d%c", temp->data, n != 1 ? ' ' : '\n');
temp->data = 0;
a = 1;
n--;
} else ++a;
temp = temp->next;
} else temp = temp->next;
}
return;
}