其他分享
首页 > 其他分享> > josephus问题->不带头节点的循环链表

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

标签:NODE,head,josephus,temp,int,pos,next,链表,节点
来源: https://blog.51cto.com/u_14582976/2829168