t3.cpp

来自「约瑟夫环:编号为1,2,3,…,n的n个人按顺时针方向围坐一圈」· C++ 代码 · 共 56 行

CPP
56
字号
#include<stdio.h>
#include<malloc.h>

typedef struct body
{int key;
 int num;
 struct body *next;
}body,*LinkList;

void main()
{
	int t,m,totalNum,j;
    LinkList L,s,p,q;
	printf("How many people are there in the circle?");
	scanf("%d",&totalNum);
	printf("please input the first number to count:");
	scanf("%d",&m);
    L=(LinkList)malloc(sizeof(body));
	printf("please input the key of body 1:");
	scanf("%d",&(L->key));
	L->num=1;
	p=L;
	for(j=2;j<=totalNum;j++)
	{
		s=(body *)malloc(sizeof(body));
		printf("please input the key of body %d:",j);
		scanf("%d",&(s->key));
		s->num=j;
		p->next=s;
		p=s;
	}
	p->next=L;
	p=q=L;
	t=1;
	while(p->next!=p)
	{
		if((t%m)!=0)
		{
			p=q;
			q=p->next;
			t++;
		}
		else
		{
			p->next=q->next;
			printf("%d   ",q->num);
			m=q->key;
			free(q);
			t=1;
			q=p->next;
		}		
     }	
	printf("%d\n",p->num);
}
 		 
	

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?