约瑟夫问题(没有头节点的循环链表)

来源:互联网 发布:mysql数据传输 编辑:程序博客网 时间:2024/04/29 06:27
#include <stdio.h>#include <stdlib.h>struct student{int id;struct student * next;};struct student * tailCreateCircleList(struct student * L,int num){//没有头节点的循环链表struct student * p, * last;L = (struct student *)malloc(sizeof(struct student));last = L;printf("请依次输入学生编号:");for(int i=0;i<num;i++){p = (struct student *)malloc(sizeof(struct student));scanf("%d",&p->id);last->next=p;last=p;p->next=NULL;}p->next=L->next;return L;}int updateList(struct student * L,int pos){struct student * p;p = L;int step=0;while(step!=pos){p=p->next;step++;}printf("%d ",p->id);p->id=0;return 0;}int menu(){int pos=0;int count=0;struct student * L;printf("请依次输入学生人数:");int n;scanf("%d",&n);L=tailCreateCircleList(L,n);int num=n;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%n+1);count=0;num--;}pos++;p=p->next;}printf("\n");free(L);return 0;}int main(){menu();return 0;}

0 0
原创粉丝点击