华为面试题——约瑟夫问题的C++简单实现(循环链表)

/*
    author:jiangxin
    Blog:http://blog.csdn.net/jiangxinnju
    Function:method of Josephus question
*/
#include <iostream>

using namespace std;

struct node
{
    int seq;
    node *next;
};
typedef struct node NODE;

void test_Josephus()
{
    /*如果共同拥有n人。从第s个人開始数数,每数到m该人出列,后面的人又一次開始数。知道所有人出列*/
    int n,s,m;
    NODE *head,*last,*current,*prev;
    cout << "Input the n,s,m(separate with space):";
    cin >> n >> s >> m;

    for(int i=1;i<=n;i++) //建立循环链表
    {
        current = new NODE;
        current->seq = i;
        current->next = head;
        if(i == 1)
        {
            head = current;
            last = current;
        }
        else
        {
            last->next = current;
            last = last->next;
        }
    }
    current = head; //遍历循环链表,输出序列
    do
    {
        cout << current->seq << " ";
        current = current->next;
    }while(current!=head);

    current = head; //将current置于第s个位置
    for(int i=1;i<s;i++)
    {
        current = current->next;
    }
    cout << endl;

    for(int i=1;i<=n;i++) //共循环n轮,得到一个总体的输出序列
    {
        for(int j=1;j<m;j++)
        {
            prev = current;
            current = current->next;
        }
        cout << current->seq << " ";
        prev->next = current->next;
        delete current;
        current = prev->next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值