题目链接http://poj.org/problem?id=3750
用链表解决的约瑟夫问题
写的比较麻烦比较长
View Code
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 struct node 5 { 6 int num; 7 char name[200]; 8 struct node*next; 9 }; 10 struct node*creat(int n) 11 { 12 int i; 13 struct node*p,*tail,*head; 14 p=(struct node*)malloc(sizeof(struct node)); 15 p->num=1; 16 scanf("%s%*c",&p->name); 17 p->next=NULL; 18 head=p; 19 tail=p; 20 for(i=2;i<=n;i++) 21 { 22 p=(struct node*)malloc(sizeof(struct node)); 23 p->num=i; 24 scanf("%s%*c",&p->name); 25 tail->next=p; 26 tail=p; 27 p->next=NULL; 28 } 29 tail->next=head; 30 return head; 31 } 32 int sel(struct node*head,int s,int m,int n) 33 { 34 int num=0,i; 35 int count=0; 36 struct node*p,*q; 37 q=head; 38 while(q->next!=head) 39 q=q->next; 40 for(i=0;i<s-1;i++) 41 {q=q->next;} 42 //printf("被删除的人的序号依次是:"); 43 while(count<n-1) 44 { 45 p=q->next; 46 num++; 47 if(num%m==0) 48 { 49 q->next=p->next; 50 printf("%s\n",p->name); 51 free(p); 52 count++; 53 } 54 else 55 q=p; 56 } 57 printf("%s",q->name); 58 } 59 int main() 60 { 61 int n,m,s; 62 struct node*head; 63 scanf("%d",&n); 64 head=creat(n); 65 scanf("%d,%d",&s,&m); 66 sel(head,s,m,n); 67 return 0; 68 }