josephus问题->不带头节点的循环链表

#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct node
{
    int data;
    struct node *next;
}NODE;
NODE* create_circlelist(int n) //建立不带头节点的循环单链表
{
    NODE* head;
    NODE* p;
    NODE* q;
    p = new NODE;
    p->data = 1;
    head = p;
    for(int i=2;i<=n;i++)
    {
        q = new NODE;
        q->data = i;
        p->next = q;
        p = q; //p永远指向最后一个节点
    }
    p->next = head;
    return head;
}
void josephus(NODE* head,int pos,int step)
{
    int i=1;
    NODE* front = NULL;
    NODE* temp = head;
    while(temp->data != pos)
    {
        temp = temp->next;
    }
    while(temp!=temp->next)
    {
        for(int i=0;i<step-1; i++)
        {
            front = temp;
            temp = temp->next;
        }
        cout<<"the"<<i++<<"kill number is:";
        cout<<temp->data<<" "<<endl;
        front->next = temp->next;
        delete temp;
        temp = front->next;
    }
    cout<<"the "<<i++<<" kill Number is:";
    cout<< temp->data<<endl;
    delete temp;
}
#if 1
int main(int n, char*m[])
{
    cout<<"input the size:";
    int size;
    cin>>size;
    cout<<"input the start pos:";
    int pos;
    cin>>pos;
    cout<<"input the circle number:";
    int step;
    cin>>step;
    NODE* head = create_circlelist(size);
    josephus(head,pos,step);
    return 0;
}
#else
int main(int n, char*m[])
{
    int size=atoi(m[1]);
    int pos =atoi(m[2]);
    int step =atoi(m[3]);
    NODE* head = create_circlelist(size);
    josephus(head,pos,step);
    return 0;
}
#endif

上一篇:购物车小程序


下一篇:2020牛客暑期多校训练营(第六场) Josephus Transform