#include <stdio.h> #include <stdlib.h> typedef struct Node{ int data; struct Node *next; }node; //创建约瑟夫环 node* create(int n){ node *head,*p,*s; int i; head = (node*)malloc(sizeof(node)); p = head; p->data = 0; p->next = p; for (i = 1; i <= n; i++){ s = (node*)malloc(sizeof(node)); p->next = s; p = p->next; p->data = i; } head = head->next; //组成环路 p->next = head; return head; } node* findNode(node *head, int index){ //环路不存在到链表尾情况 while (--index){ head = head->next; } return head; } node* delNode(node *head, int index){ node *p, *s; index--; while (--index) { head = head->next; } p = head->next; head->next = p->next; free(p); return head->next; } void main(){ node *mylist; mylist = create(10); //找到开始位置 node *start = findNode(mylist, 1); //只剩最后一个元素时必然指向自身 while (start!=start->next) { //更新开始位置 start=delNode(start,2); }
printf("%d",start->data); }
公式法:
-
f[1]=0; f[i]=(f[i-1]+m)%i; (i>1)
-
f[1]=1; f[i]=(f[i-1]+m)%i (i>1); if(f[i]==0) f[i]=i;
-
P(1, m, k)=1 (i = 1); P(i, m, k)=[P(i - 1, m, k ) + m - 1] % i + 1 (i > 1, 此处先减1是为了让模i的值不为0)