约瑟夫问题
来源:互联网 发布:香港电台在线收听软件 编辑:程序博客网 时间:2024/06/06 10:07
问题描述:39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被敌人抓到,于是决定了一个自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止
思路:利用循环链表遍历输出自杀顺序
#include "stdio.h"#include "stdlib.h"typedef struct node{ int data; struct node* next;}node;node *create(int n){ node *head, *p = NULL; head = (node*)malloc(sizeof(node)); p = head; node *s; int i = 1; if ( 0 != n) { while( i <= n ) { // 建立循环链表,结点依次为1,2,... s = (node*)malloc(sizeof(node)); s->data = i++; p->next = s; p = s; } s->next = head->next; } //释放头结点 free(head); return s->next;}int main(int argc, char const *argv[]){ int n = 41; //总人数 int m = 3; //循环次数 node *p = create(n); node *temp; int i; while(p != p->next) { for (i = 1; i < m-1; i++) { p = p->next; } printf("%d->", p->next->data); temp = p->next; p->next = temp->next; free(temp); p = p->next; } printf("%d\n", p->data); return 0;}