/* * Josephus问题: * 设有n个人围坐一个圆桌周围,现从第1个人开始报数,数到第m的人出列, * 然后从出列的下一个重新开始报数,数到第m的人又出列……如此重复,直 * 到所有的人全部出列为止。 * 对任意给定的n、m,求按出列次序得到的n个人员的顺序表。 */ /* 链表 */ typedef struct LNode { int elem; struct LNode *next; } *LinkList; void create_link_list(struct LNode **listptr, int n) { struct LNode *list = (struct LNode *) malloc(sizeof(struct LNode)); list->elem = -1; list->next = NULL; struct LNode *elem = NULL; struct LNode *current = list; int i = 0; for (; i < n; i++) { elem = (struct LNode *) malloc(sizeof(struct LNode)); elem->elem = i; elem->next = NULL; current->next = elem; current = current->next; } current->next = list; *listptr = list; } int Josephus(int n, int m) { //创建循环链表 struct LNode *list = NULL; create_link_list(&list, n); //查找第m个人(编号从0开始,第m个人即是编号为m-1的那个人) struct LNode *current = list->next; int i = 0; for (; list->next != list; i++) { if (i == m - 2) { //删除第m-1号元素 if (current->next == list) { current = list; } struct LNode * temp = current->next; current->next = temp->next; current = current->next; fprintf(stdout, "deleted Node:{elem==%d/tnext==%u}/n", temp->elem, temp->next); free(temp); i = -1; continue; } if (current == list) { current = list->next; i--; } else if (current->next == list) { current = list->next; } else { current = current->next; } } }
Josephus问题求解
最新推荐文章于 2022-01-22 16:59:01 发布