程序:
//约瑟夫问题,用循环链表
#include <stdio.h>
#include <stdlib.h>
typedef struct node* link;
struct node
{
int item;
link next;
};
int main()
{
int N; //N表示有多少人
int M; //M表示计数有多少
int i;
int j;
scanf("%d%d",&N,&M);
link head = (link)malloc(sizeof(*head));
head->item = 1;
head->next = head;//设置循环链表
link tmp = head;
for(i = 2;i <= N;i++)
{
link temp = (link)malloc(sizeof(*temp));
temp->item = i;
tmp->next = temp;
temp->next = head;
tmp = temp;
}
//开始计数
//也可以使用while(tmp != tmp->next)
for(i = 2;i <= N;i++)
{
for(j = 1;j < M;j++)
{
tmp = tmp->next;
}
link temp = tmp->next;
tmp->next = tmp->next->next;
printf("%d ",temp->item);
free(temp);
}
printf("\nfinally people:%d\n",tmp->item);
free(tmp);
return 0;
}