约瑟夫环报数问题

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

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

#ifndef SQQUEUE_H_INCLUDED
#define SQQUEUE_H_INCLUDED
#include
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<<"淘汰编号的序列"<     while(n != 1)
    {
        if(s == 0)
        {
            for(j = 1;j             {
                Q.front = Q.front->next;
                s++;
            }
        }
        else
        {
            for(j = 1;j             {


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

#include
using namespace std;
#include "SqQueue.h"


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


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


    return 0;
}

你可能感兴趣的:(约瑟夫环报数问题)