约瑟夫问题(单链表)

#include <stdio.h>
#include <stdlib.h>

struct student{
	int id;
	struct student * next;
};

struct student * tailCreateList(){
	struct student * L,* p, * last;
	L = (struct student *)malloc(sizeof(struct student));
	last = L;
	int x;
	scanf("%d",&x);
	while(x!=-1){
		p = (struct student *)malloc(sizeof(struct student));
		p->id=x;
		last->next=p;
		last=p;
		p->next=NULL;
		scanf("%d",&x);
	}
	return L;
}

int studentNum(struct student * L){
	int num=0;
	struct student * p;
	p = L->next;
	while(p!=NULL){
		num++;
		p=p->next;
	}
	return num;
}

int updateList(struct student * L,int pos){
	struct student * p;
	p = L;
	int step=0;
	while(p!=NULL&&step!=pos){
		p=p->next;
		step++;
	}
	printf("%d ",p->id);
	p->id=0;
	return 0;
}

void display(struct student * L){
	struct student * p;
	p=L->next;
	while(p!=NULL){
		printf("%d ",p->id);
		p=p->next;
	}
	printf("\n");
}

int menu(){
	int pos=0;
	int count=0;
	struct student * L;
	printf("请依次输入学生编号:");
	L=tailCreateList();
	printf("学生编号依次为:");
	display(L);
	int num=studentNum(L);
	printf("一共有学生%d人\n",num);
	printf("规定学生从1到m报数,报到m的退出!\n");
	printf("请输入m值:");
	int m;
	scanf("%d",&m);
	struct student * p;
	p = (struct student *)malloc(sizeof(struct student));
	p = L->next;
	printf("依次出局的学生为:");
	while(num>1){
		if(p->id!=0){
			count++;
		}
		if(count==m){
			updateList(L,pos+1);
			count=0;
			num--;
		}
		pos++;
		p=p->next;
		if(pos==studentNum(L)){
			pos=0;
			p=L->next;
		}
	}
	printf("\n");
	for(p=L->next;p!=NULL;p=p->next){
		if(p->id!=0){
			printf("获胜者id: %d\n",p->id);
		}
	}
	free(L);
	return 0;
}

int main(){
	menu();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值