您的位置:首页 > 其它

约瑟夫问题(单链表)

2014-04-07 23:11 190 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: