约瑟夫环报数问题

有n个人围成一圈,从第1个人开始,1,2,…,m报数,报至m出局,余下的人继续从1,2,…,m报数,重复之前的流程,要求:求出被淘汰编号的序列,及最后剩下的一人是原来的第几号?

如题,用一个循环链表(队列),在设置一个计数器,让链表的首尾相连,循环n-1次,每次让指针向后移动m-1个位置,删除当前节点,删除n-1次后只剩一个数据,就是保留的数据

#ifndef SQQUEUE_H_INCLUDED
#define SQQUEUE_H_INCLUDED
#include<iostream>
typedef int Status;
typedef int ElemType;
typedef struct QNode
{
    ElemType data;
    struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
    QueuePtr front;
    QueuePtr rear;
}LinkQueue;
Status InitQueue(LinkQueue &Q)
{
    Q.front = Q.rear=new QNode;
    if(!Q.front)
    {
        return 0;
    }
    Q.front->next = NULL;
return 1;
}
Status EnQueue(LinkQueue &Q,ElemType e)
{
    QueuePtr p;
    p = new QNode;
    if(!p)
    return 0;
    p -> data = e;
    p -> next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    return 1;
}
Status DeQueue(LinkQueue &Q,ElemType &e)
{
    QueuePtr p;
    p = new QNode;
    p = Q.front->next;
    e = p->data;
    Q.front->next = p->next;
    if(Q.rear == p)
    {
        Q.rear = Q.front;
    }
    delete p;
    return 1;
}
void Main(LinkQueue &Q,int n,int m,int e)
{
    Q.front = Q.front->next;
    Q.rear->next = Q.front;
    int j,s=0;
    cout<<"淘汰编号的序列"<<endl;
    while(n != 1)
    {
        if(s == 0)
        {
            for(j = 1;j<m-1;j++)
            {
                Q.front = Q.front->next;
                s++;
            }
        }
        else
        {
            for(j = 1;j<m;j++)
            {


                Q.front = Q.front->next;
            }
        }
        DeQueue(Q,e);
        cout<<e<<" ";
        n--;
}
    cout<<endl;
    cout<<"最后剩下的一人是原来的第"<<Q.front->data<<"号"<<endl;
}
#endif // SQQUEUE_H_INCLUDED

#include <iostream>
using namespace std;
#include "SqQueue.h"


int main()
{
    LinkQueue Q;
    int i,n,m,e;


    InitQueue(Q);
    cout<<"请输入人数:"<<endl;
    cin>>n;
    for(i=1;i<=n;i++)
        EnQueue(Q,i);
  
    cout<<"请输入出局数字:"<<endl;
    cin>>m;
    Main(Q,n,m,e);


    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值