# 牛逼！一行代码解决约瑟夫环问题！

## 数组

#include <stdio.h>

int main()
{
int num, person;
int flag[1024] = {0};        //标志位，表示人在不在圈内
int k = 0, i = 1;            //k计数器 i数组下标，初始化成1，表示第一个人

printf("Pleaes input...\n");
scanf("%d", &num);

person = num;

while (1)
{
if (flag[i] == 0)       //人在圈内
{
k++;
if (k == 3)        //报数为3
{
k = 0;         //k回到0
flag[i] = 1;   //踢出
person--;
}
}
i++;
if (i == num + 1)
{
i = 1;
}
if (1 == person)
{
break;
}
}

for (i = 1; i <= num; i++)
{
if (flag[i] == 0)
{
printf("%d\n", i);
break;
}
}

return 0;
}

## 单向循环链表

#include <stdio.h>
#include <stdlib.h>

struct Node
{
int data;                      //数据域
struct Node *next;             //指针域
};
typedef struct Node Node;

/*

*/
{
if (p <= 0)
{
return NULL;
}

Node *h = (Node *)malloc(sizeof(Node) * 1);
if (NULL == h)
{
return NULL;
}
h->data = 1;                   //节点的编号
h->next = h;                   //形成循环链表

Node *q = h;
int i;
for (i = 0; i < p - 1; i++)
{
Node *m = (Node *)malloc(sizeof(Node) * 1);
if (NULL == m)
{
return NULL;
}
m->data = i + 2;
m->next = h;
q->next = m;
q = m;
}

return h;
}

/*

*/
{
int length = 1;
Node *p = h->next;

while (p != h)
{
length++;
p = p->next;
}

return length;
}

/*

*/
Node *DeleteNode(Node *p)
{
Node *m = p;
while(m->next != p)
{
m = m->next;
}

m->next = p->next;
free(p);

return m->next;
}

/*

*/
int Joseph(Node *h)
{
if (NULL == h)
{
return -1;
}

int k = 0;
Node *p = h;
while (LinkLength(p) != 1)
{
k++;
if (3 == k)
{
k = 0;
p = DeleteNode(p);            //节点从链表中删除 返回下一个节点的地址
}
else
{
p = p->next;
}
}

return p->data;
}

int main()
{
int person;                    //记录人数

printf("请输入人数：\n");
scanf("%d", &person);

if (NULL == head)
{
printf("单链表创建失败!\n");
exit(1);
}

int last = Joseph(head);                       //处理约瑟夫环

printf("最后一个士兵是%d\n", last);
return 0;
}



## 递归

old = (new + 2) % n + 1;

int Joseph(int n)
{
if (1 == n) return 1;
return (Joseph(n - 1) + 2) % n + 1;
}

#include <stdio.h>

int Joseph(int n)
{
return (n == 1) ? n : ((Joseph(n - 1) + 2) % n + 1);
}

int main()
{
int person;

printf("请输入人数：\n");
scanf("%d", &person);

printf("最后一个士兵 %d\n", Joseph(person));

return 0;
}

11-26
07-17 1万+

01-25 412
01-31 2万+
07-12
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试