zoukankan      html  css  js  c++  java
  • 华为面试题——约瑟夫问题的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;
        }
    }

  • 相关阅读:
    字符串前面加@
    SQL字段类型bit 查询时注意
    SELECT IDENT_CURRENT(tableName)和自增长列的纠结
    解析xml文件 selectSingleNode取不到节点
    【.NET】.NET MVC4 微信扫一扫功能实现附全部代码
    未定义对象
    C# Web开发中弹出对话框的函数[转载]
    json序列化和反序列化
    jq的$.each()方法
    学习URLRewriter.dll的使用
  • 原文地址:https://www.cnblogs.com/lytwajue/p/6719479.html
Copyright © 2011-2022 走看看