# C++之约瑟夫环

(一)数组解决

#include "stdio.h"
int main()
{
const int N_man =41;      //人数
int arr[N_man] = {0};     //初始化每一个都为0
int num = 0;
int k = 1;
int i = 0;
for (i = 0; i<N_man; i++)
{
printf("%d\t", arr[i]);
}
printf("\n");
while (num<N_man-2)
{
if (arr[i] == 0)
{
k+=1;
if (k == 3)
{
num += 1;
k = 0;
arr[i] = num;

}

}
i = (i + 1) % N_man;
}
for ( i=0;i<N_man;i++)
{
printf("%d\t ",arr[i]);
}
return 0;
}

(二)链表解决

* 结构体和函数声明 */
typedef struct _node_t
{
int             n_num;
int             passwd;
struct _node_t *next;
} node_t;

/* 功能函数实现 */

/*
*  name: node_t_create
*  params:
*    n         [in]        输入要构造的链表的个数
*  return:
*    返回构造成功的环形单向链表指针
*  notes:
*    构造节点数量为 n 的环形单向链表
*
*/
node_t * node_t_create(int n,int key[])
{
node_t *p_ret   = NULL;

if (0 != n)
{
int     n_idx   = 1;
node_t *p_node  = NULL;

/* 构造 n 个 node_t */
p_node = (node_t *) malloc(n * sizeof(node_t));
if (NULL == p_node)
return NULL;
else
memset(p_node, 0, n * sizeof(node_t));

/* 内存空间申请成功 */
p_ret = p_node;
for (; n_idx < n; n_idx++)
{
p_node->n_num = n_idx;
p_node->passwd = key[n_idx];
p_node->next = p_node + 1;
p_node = p_node->next;
}
p_node->n_num = n;
p_node->passwd = key[n];
p_node->next = p_ret;
}

return p_ret;
}

/*
*  name: main
*  params:
*    none
*  return:
*    int
*  notes:
*    main function
*/
int main()
{
int     n, m;
node_t *p_list, *p_iter;
int *key;

printf("input two integers:");
scanf("%d %d",&n,&m);

key =(int *) malloc(n * sizeof(int));
int j = 1;
for(;j <= n; ++j)
scanf("%d",key+j);

/* 构造环形单向链表 */
p_list = node_t_create(n,key);

/* Josephus 循环取数 */
p_iter = p_list;
int k = 1;
int l = 1;

/* 取到第 m-1 个节点 */
for (; l < m - 1; l++)
{
p_iter = p_iter->next;
}

/* 输出第 m 个节点的值 */
printf("%d/n", p_iter->next->n_num);

m = p_iter->next->passwd;//保存将要删除的节点key值，作为下一次的密码用

/* 从链表中删除第 m 个节点 */
p_iter->next = p_iter->next->next;
p_iter = p_iter->next;

while (p_iter != p_iter->next)
{
int i   = 1;

/* 取到第 m-1 个节点 */
for (; i < m - 1; i++)
{
p_iter = p_iter->next;
}

/* 输出第 m 个节点的值 */
printf("%d/n", p_iter->next->n_num);
m = p_iter->next->passwd;
/* 从链表中删除第 m 个节点 */
p_iter->next = p_iter->next->next;
p_iter = p_iter->next;
}
printf("%d/n", p_iter->n_num);

/* 释放申请的空间 */
free(p_list);
return 0;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120