一位叫约瑟夫的将军,战斗中,连同手下士兵一起被敌人俘虏了,
手下的士兵宁死不投降,所以,约瑟夫将军想出了一个办法,
让大家站成一个圈,从第一个人开始数数,谁数到7了,谁就自杀,
自杀之后,他的下一个人重新从1开始数,遇到7,再自杀,直到最后只能剩下一个人。
最后活下来的是约瑟夫,然后他不想死,他投降了。
这种圈,在现今社会中被叫做,"约瑟夫环"。
要求,编写程序,命令行 输入 总人数(>=2) 及 数到几(>=2)自杀,
程序自动计算,将第 n 次 杀掉的 第m个人输出
最后再输出剩下的是几号。
例如:
输入 5人 数到3 自杀,
程序输出:
第 1 次杀的人是 3 号;
第 2 次杀的人是 1 号;
第 3 次杀的人是 5 号;
第 4 次杀的人是 2 号;
最后剩下的是 4 号。
- #ifndef _MYHEAD_H_
- #define _MYHEAD_H_
-
- #include
- #include
-
- typedef struct _NODE{
- int data;
- struct _NODE *next;
- }looplist;
-
- looplist* looplistCreate();
- int looplist_inputdata(looplist* phead,int value);
- void looplistshow_info(looplist* phead);
- looplist* looplist_cutHead(looplist* phead);
- #endif
- #include "myhead.h"
-
- looplist* looplistCreate()
- {
- looplist* phead;
- phead=(looplist*)malloc(sizeof(looplist));
- phead->data=0;
- phead->next=phead;
-
- return phead;
- }
-
- int looplist_inputdata(looplist* phead,int value)
- {
- if(phead==NULL){
- printf("传参错误\n");
- return -1;
- }
-
-
- looplist* temp=(looplist*)malloc(sizeof(looplist));
-
- temp->data=value;
- temp->next=NULL;
-
- temp->next=phead->next;
- phead->next=temp;
-
- return 0;
- }
-
- int looplist_delete(looplist* phead)
- {
- if(phead==NULL){
- printf("传参错误\n");
- return -1;
- }
-
-
- }
-
- looplist* looplist_cutHead(looplist* h)
- {
- if(h==NULL){
- printf("传参错误\n");
- exit(-1);
- }
-
- looplist* p=h;
-
- while(h->next!=p){
- h=h->next;
- }
-
- h->next=p->next;
-
- free(p);
- p=NULL;
-
- return h->next;
- }
-
- void looplistshow_info(looplist* phead)
- {
- if(phead==NULL){
- printf("传参错误\n");
- return ;
- }
-
- looplist* flag=phead;
-
- while(phead->next!=flag){
- printf("%d ",phead->data);
- phead=phead->next;
- }
- printf("%d\n",phead->data);
- }
- #include "myhead.h"
-
- void yuesefu(int n,int k,int m)
- {
- looplist* phead = looplistCreate();
-
- for (int i = n; i>=1; i--){
- looplist_inputdata(phead,i);
- }
-
- phead = looplist_cutHead(phead);
-
- for (int i = 0; i < k-1; i++){
- phead = phead->next;
- }
- //printf("%d\n",phead->data);
-
- looplist* temp;
-
- while (phead->next != phead){
- for (int i = 0; i < m-2;i++){
- phead = phead->next;
- }
-
- temp = phead->next;
- phead->next = temp->next;
-
- printf("%d ",temp->data);
-
- free(temp);
- temp = NULL;
-
- phead = phead->next;
- }
- printf("%d\n", phead->data);
- free(phead);
- phead = NULL;
- }
-
-
- int main(int argc,char const* argv[])
- {
-
- yuesefu(5,1,3);
- return 0;
- }