循环链表解决Joseph环问题

/*循环链表解决Joseph环问题*/

#include <iostream>

using namespace std;



typedef struct LNode{

    int data;

    struct LNode *next;

}LNode,*LinkList;



void Joseph(int n, int k, int m,int *result)/*n个人,从第k个开始报数1,数到m出列,然后从下个人继续开始,直至所有人都出列,输出序列保存到result数组中*/

{

    LinkList list = new LNode;

    list->data = 1;

    list ->next = list;

    LNode *cur = list;

    

    for(int i = 2; i<=n; i++)//尾插法

    {

        LNode *t = new LNode;

        t->data = i;

        t->next = cur->next;

        cur->next = t;

        cur = t;

    }//此时cur指向最后一个结点



    //跳到第k个人处

    LNode *r ,*p = list;

    while(--k) r = p,p = p->next;



    //循环步进m,输出元素并删除,直至list为空

    while(n--)

    {

        for(int s = m;--s;r = p,p = p->next);

        r->next = p->next;

        cout<<p->data<<"    ";

        result[n] = p->data;

        delete p;

        p = r->next;//从下一个继续开始

    }

    cout<<endl;

}



int main()

{

    int result[10];

    Joseph(10,3,5,result);

    for(int i = 0; i<10; i++)

        cout<<result[9-i]<<"    ";

    cout<<endl;

}

 

你可能感兴趣的:(OS)