PTA作业10约瑟夫问题7-7

题目

#include
#include
struct node{
	int data;
	struct node *next;
}*head,*p,*las,*q,*p2,*head2;
int n,m,i,j,m2;
void append(struct node **p,int x){
	(*p)->data=x;
	(*p)->next=(struct node*)malloc(sizeof(struct node));
	las=*p,*p=(*p)->next;
}
int main(){
	scanf("%d",&n);
	head=(struct node*)malloc(sizeof(struct node));
	p=(struct node*)malloc(sizeof(struct node));
	head->next=p;
	for (i=1;i<=n;i++) append(&p,i);
	las->next=head->next;
	
	while (~scanf("%d",&m)){
		head2=(struct node*)malloc(sizeof(struct node));
		p2=(struct node*)malloc(sizeof(struct node));
		head2->next=p2;
		p=head;
		for (i=1;i<n;i++){
			for (j=1;j<m;j++) p=p->next;
			append(&p2,p->next->data);
			q=p->next;
			p->next=p->next->next;
			free(q);
		}
		append(&p2,p->next->data);//m=1时p始终等于head
		las->next=head2->next;
		free(p->next);
		free(head);
		p=p2,head=head2;
	}
	p=head;
	for (i=1;i<=n;i++) p=p->next,printf("%4d",p->data);
}

你可能感兴趣的:(杂,算法,数据结构,c++)