编辑代码

//约瑟夫环.cpp 

#include<stdio.h>
#include<malloc.h>
struct node
{
	int data;
	struct node* next;
}; 
struct node *p,*q,*head,*tail;
void create(int m,int n,struct node* head)
{
	if(m<=0||n>m)
	{
		free(head);
		printf("ERROR!");
	}
	else 
	{
		int i=1;
		tail=head;
		for(i=1;i<=m;i++)
		{
			p=(struct node* )malloc(sizeof(struct node));
			p->data=i;
			tail->next=p;//用tail表示当前链表中最后一个结点 
			p->next=head->next;//形成循环 
			tail=p;
		}
		p=p->next;//把p指到首元结点 
	}
}
int main()
{
	int m;//链表有m个结点 
	int s,n;//从第s个结点开始计数为1
	int count=1;//记录共输出了多少个数 
	int flag=0;//记录数到了1~n中的第几个结点 
	int i;//用于各种循环 
	printf("请按照形式“m s n”输入链表结点个数、开始节点及循环数:"); 
	scanf("%d %d %d",&m,&s,&n);
	head=(struct node* )malloc(sizeof(struct node));//头结点 
	head->data=-1,head->next=NULL;//初始化 
	create(m,s,head);//建立有m个结点的循环链表
	p=head->next;
	q=tail;//初始化 
	for(i=1;i<s;i++)
	{
		p=p->next;
		q=q->next;
	}//让p指在第s个结点上
	while(count<=m)
	{
		for(flag=1;flag<n;flag++)
		{
			p=p->next;
			q=q->next;
		}
		printf("%d ",p->data);
		q->next=q->next->next;
		free(p);//将输出过的节点删除并释放相应内存 
		p=q->next;
		count++;
	 } 
	 return 0;
 }