约瑟夫问题(Josephus Problem)也称“丢手绢问题”,是一道非常经典的算法问题,其解法涉及了链表、递归等算法和数据结构,本文主要分为如下三个内容:
使用C语言定义循环链表,通过遍历链表模拟事件处理过程;
使用数学方法,找出第n - 1步与第n步的关系,通过递归解决问题;
对第二种方法进行优化,加速递归过程,提高算法效率
循环链表(C语言)
代码
#include
#include
//定义循环链表
typedef struct node//定义node结构体
{
int data;
struct node* next;
}cLinkList;//typedef struct node* cLinkList;定义一个struct node类型的循环链表
//主函数
int main()
{
cLinkList *head, *p, *s, *temp;
int n, k;
int i = 1;
printf("Please enter the total number n:\n");
scanf("%d", &n);
printf("Please enter the key value:\n");
scanf("%d", &k);
k %= n;
head = (cLinkList *)malloc(sizeof(cLinkList));