程序代码:/*
程序采用循环链表的算法实现
m个人围成圈,报到n的人退出,求最后一位的原始编号
*/
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
long int m,n;
struct node *h;
struct node /*链表结点结构*/
{
struct node *next;
int data;
};
struct node * create(struct node *h) /*创建单向循环链表*/
{
struct node *p,*q; int i;
h=p=q=(struct node *)malloc(sizeof(struct node));
p->next=NULL; p->data=1;
for(i=2;i<=m;i++)
{
p=(struct node *)malloc(sizeof(struct node));
q->next=p; p->data=i; p->next=NULL;
q=p;
}
p->next=h;
return h;
}
int fun(struct node *h) /*操作链表*/
{
struct node *p=h,*q; int i;
if(n>1)
{
while(p->next!=p)
{
i=1;
while(i<n-1) {p=p->next; i++;}
q=p->next;
p->next=q->next;q->next=NULL;
free(q);
p=p->next;
}
}
else if(n==1)
{
p->data=m;
}
return p->data;
}
int main()
{
struct node *h;
printf("请输入总人数m:");
scanf("%d",&m);
printf("再输入退出者号n:");
scanf("%d",&n);
h=create(h);
printf("最后一位号码是:");
printf("%d\n",fun(h));
return 0;
}这是论坛里的大神写的,我收藏的,你参考着写吧!约瑟夫循环

最基础的往往是你最容易忽略的!



