C++循环链表之约瑟夫环

#include <cstdio>
#include <iostream>
#include <cstdlib>

using namespace std;

struct node
{
    int index;
    node * next;
};
typedef node * LNode;
class CLL
{
    public:
        LNode head = NULL;
    public:
        static LNode getnew()//get new node or point
        {
	        LNode L;
	        if (L=(LNode)malloc(sizeof(node)))
		        {L->next=NULL;return L;}
	        else {
	            cout << "memory error"<<endl;
	            exit(-1);
	        }
        }
        void print()
        {
            LNode L = head;
            if (!L) cout << "Unlickily , it's empty" << endl;
            cout << L->index;
            L->next?cout<<"->":cout<<endl;
            LNode tail = L->next;
            while(tail != L){
                cout<<tail->index;
                tail->next!=L?cout<<"->":cout<<endl;
                tail=tail->next;
            }
        }
        CLL(int n)
        {
            if (n<=0) exit(-1);
            head = getnew();
            head->index=0;
            LNode tail = head;
            for (int i=1;i<n;i++)
            {
                tail->next = getnew();
                tail->next->index=i;
                tail = tail->next;
            }
            tail->next=head;
        }
        void circle(int m)
        {
            int cnt=0;
            LNode t = head;
            LNode b = NULL;
            while (t->next!=t)
            {
                cnt++;
                if (cnt == m) 
                {
                    b->next = t->next;
                    free(t);
                    t = b;
                    cnt=0;
                }
                b = t;
                t = t->next;
            }
            cout << t->index+1 << endl;
        }
};

int main()
{
    int n;
    cin >> n;
    CLL cll(n);
    cll.print();
    int m;
    cin >> m;
    cll.circle(m);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值