约瑟夫问题 - 循环链表求解

约瑟夫问题求解

n 个人围成一个圆圈,首先第 1 个人从 1 开始一个人一个人顺时针报数,报到第 m 个人,令其出列。然后再从下一 个人开始从 1 顺时针报数,报到第 m 个人,再令其出列,…,如此下去,求出列顺序。

代码编写如下:

int main() 
{
    CircleList* list = CircleList_Create();

    int index = 0;
    int i = 0;
    int m = 3;

    struct Value v1;
    struct Value v2;
    struct Value v3;
    struct Value v4;
    struct Value v5;
    struct Value v6;
    struct Value v7;
    struct Value v8;

    v1.v = 1;
    v2.v = 2;
    v3.v = 3;
    v4.v = 4;
    v5.v = 5;
    v6.v = 6;
    v7.v = 7;
    v8.v = 8;

    CircleList_Insert(list, (CircleListNode*) &v1, CircleList_Length(list));
    CircleList_Insert(list, (CircleListNode*) &v2, CircleList_Length(list));
    CircleList_Insert(list, (CircleListNode*) &v3, CircleList_Length(list));
    CircleList_Insert(list, (CircleListNode*) &v4, CircleList_Length(list));
    CircleList_Insert(list, (CircleListNode*) &v5, CircleList_Length(list));
    CircleList_Insert(list, (CircleListNode*) &v6, CircleList_Length(list));
    CircleList_Insert(list, (CircleListNode*) &v7, CircleList_Length(list));
    CircleList_Insert(list, (CircleListNode*) &v8, CircleList_Length(list));    

    CircleList_Reset(list); 

    while( CircleList_Length(list) > 0 )
    {
        struct Value* pv = NULL;

        for(i=1; i<3; i++)
        {
            CircleList_Next(list);
        }

        pv = (struct Value*)CircleList_Current(list);

        printf("%d\n", pv->v);

        CircleList_DeleteNode(list, (CircleListNode*)pv);
    }

    CircleList_Destroy(list);

    //本程序 到 m = 3 时报数, 结果:3 6 1 5 2 8 4 7  

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值