/*选首领(此程序在WIN-TC下通过)*/
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{ int code;
struct node *next;
}node,*linklist;
linklist create_list1(int n) /*尾插法创建单循环链表*/
{ int i;
linklist head,p,q;
head=(node *)malloc(sizeof(node));
head->code=n;
head->next=head;
q=head;
for(i=n-1;i>=1;i--)
{ p=(node *)malloc(sizeof(node));
p->code=i;
p->next=head;
q->next=p;q=p;
}
return head;
}
linklist create_list2(int n) /*前插法创建单循环链表*/
{ int i;
linklist head,p;
head=(node *)malloc(sizeof(node));
head->code=1;
head->next=head;
for(i=n;i>1;i--)
{ p=(node *)malloc(sizeof(node));
p->code=i;
p->next=head->next;
head->next=p;
}
return head;
}
void output(linklist head) /*输出单循环链表*/
{ linklist p;
p=head;
printf("The list of the member's flag:/n");
do
{ printf("%d/n",p->code);
p=p->next;
}while(p!=head);
printf("/n");
}
void play(linklist head ,int n) /*选首领的具体实现*/
{ linklist p=head,q;
int c=1,k=n;
while(k>1)
{ if(c==2)
{ q=p->next;p->next=q->next;
printf("/nThe %d member has been went out./n",q->code);
free(q);c=0;k--;
}
else
{ p=p->next;c++;}
}
printf("/nCongratulations!/nThe %d member is the winner!",p->code);
}
main()
{ int n;
linklist head;
printf("Please input people's number:");
scanf("%d",&n);
head=create_list1(n);
output(head);
play(head,n);
}