約瑟夫環——鏈表法

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章