//1.0
#include<stdio.h>
#include<stdlib.h>
#define N 10
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*t,*p;
h=NULL;
for(int i=0;i<N;i++){
p=(ElemSN *)malloc(sizeof(ElemSN));
p->data=a[i];
if(!h){
p->next=p;
h=t=p;
}
else{
p->next=h;
t=t->next=p;
}
}
return h;
}
ElemSN *Tosephus(ElemSN *h,int s)
{
ElemSN *p,*q;
p=h;
int cnt=0;
while(p->next!=p){
cnt++;
if(cnt%s==0){
q->next=p->next;
//移头
if(p==h){
h=h->next;
//printf("%d",p->data);验证输出元素
free(p);//p释放,需重新指上来
p=h;
}
else{
//删中间尾
//printf("%d",p->data);
free(p);
p=q->next;
}
}
else{//联动
q=p;
p=p->next;
} }
return p;
}
int main()
{
int a[N],i,s;
printf("请输入10个整数:");
for(i=0;i<N;i++){
//scanf("%d",&a[i]);
a[i]=i+1;
}
printf("\n");
printf("请输入s:");//输入孩子数
scanf("%d",&s);
ElemSN *head=NULL,*t;
//创建单向循环链表
head=Createlink(a);
//实现约瑟夫环
t=Tosephus(head,s);
printf("%d",t->data);
return 0;
}
//2.0
#include<stdio.h>
#include<stdlib.h>
#define N 10
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*t,*p;
h=NULL;
for(int i=0;i<N;i++){
p=(ElemSN *)malloc(sizeof(ElemSN));
p->data=a[i];
if(!h){
p->next=p;
h=t=p;
}
else{
p->next=h;
t=t->next=p;
}
}
return h;
}
ElemSN *Tosephus(ElemSN *h,int s)
{
ElemSN *p,*q;
int cnt;
p=h;
do{
for(cnt=1;cnt%s!=0;cnt++,q=p,p=p->next);//到第s个元素跳出循环,p指向第s个元素
q->next=p->next;//挂链
free(p);//删除
p=q->next;//
}while(p->next!=p);
return p;
}
int main()
{
int a[N],i,s;
printf("请输入10个整数:");
for(i=0;i<N;i++){
//scanf("%d",&a[i]);
a[i]=i+1;
}
printf("\n");
printf("请输入s:");
scanf("%d",&s);
ElemSN *head=NULL,*t;
//创建单向循环链表
head=Createlink(a);
//实现约瑟夫环
t=Tosephus(head,s);
printf("%d",t->data);
return 0;
}