小孩报数问题
N个小孩围成一圈,给他们从1开始依次编号,现指定从第W个开始报数,报到第S个时,该小孩出列,然后从下一个小孩开始报数,仍是报到S个出列,如此重复下去,直到所有的小孩都出列(总人数不足S个时将循环报数),求小孩出列的顺序。
 
输入:
       第一行输入小孩的人数NN<=64
接下来每行输入一个小孩的名字(人名不超过15个字符)
最后一行输入W,SW<N),用逗号”,”间隔
 
输出:
       按人名输出小孩按顺序出列的顺序,每行输出一个人名
 
样例输入:
5
Xiaoming
Xiaohua
Xiaowang
Zhangsan
Lisi
2,3
 
样例输出:
Zhangsan
Xiaohua
Xiaoming
Xiaowang
Lisi
 
提示:
可用链表来实现
 
考察重点:约瑟夫算法、链表
 
参考代码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
 
#define MAX_NAME_LEN 16
 
typedef struct _child {
    char name[MAX_NAME_LEN];
    struct _child * pre;
    struct _child * next;
} Child;
 
Child* init(Child* init_child) {
    if (init_child == NULL) {
        return;
    }
    init_child->pre = init_child;
    init_child->next = init_child;
    return init_child;
}
 
void append(Child* list, Child* new_child) {
    if (list == NULL || new_child == NULL) {
        return;
    }
   
    new_child->pre = list->pre;
    new_child->next = list;
    list->pre->next = new_child;
    list->pre = new_child;
}
 
void select_child(Child* list, int begin, int sel, int count) {
    int i;
    // selecting begins from the 'sel'th child
    for (i=1; i<begin; i++) {
        list = list->next;
    }
    while (count--) {
        for (i=1; i<sel; i++) {
            list = list->next;
        }
        printf("%s\n", list->name);
        list->pre->next = list->next;
        list->next->pre = list->pre;
        list = list->next;
    }
}
 
int main()
{
    int count;
    scanf("%d", &count);
   
    Child* p = (Child*)malloc(sizeof(Child) * count);
    memset(p, 0, sizeof(Child) * count);
    scanf("%s", p->name);
    Child* list = init(p);
    int i;
    for (i=1; i<count; i++) {
        Child* new_child = (Child*)(p+i);
        scanf("%s", new_child->name);
        append(list, new_child);
    }
    
    int begin, sel;
    scanf("%d,%d", &begin, &sel);
    select_child(list, begin, sel, count);
  
    free(p);
    return 0;
}