首页 > 其他 > 详细

约瑟夫环——链表法

时间:2018-04-25 10:05:40      阅读:205      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <stdlib.h>

using namespace std;

typedef struct node* list;
struct node
{
    int Item;
    list next;
};

static void DisplayList(list head)
{
    if (head->next == nullptr)
    {
        cout << "null\n";
        return;
    }
    list p = head;
    do 
    {
        cout << p->Item << endl;
        p = p->next;
    } while (p != head);
}

int main(int argc, char *argv[])
{
    int N = atoi(argv[1]);
    int M = atoi(argv[2]);

    list head = (list)malloc(sizeof(struct node));
    list p = head;

    head->Item = 1;
    head->next = head;

    for (int i=2; i<=N; i++)
    {
        list m = (list)malloc(sizeof(struct node));
        p->next = m;
        m->Item = i;
        m->next = head;
        p = m;
    }
    DisplayList(head);

    while(p != p->next)
    {
        for (int i=1; i<M; i++)
        {
            p = p->next;
        }
        cout << p->next->Item << endl;
        p->next = p->next->next;

    }
    cout << p->Item << endl;
}

 

约瑟夫环——链表法

原文:https://www.cnblogs.com/cnpirate/p/8940013.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!