zoukankan      html  css  js  c++  java
  • 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

    关注公众号 海量干货等你
  • 相关阅读:
    Postman几种常用方式
    PL/SQL 循环结构
    【oracle】解锁oracle用户,unlock
    四则运算题2
    有关Botton的用法(一)
    SQLiteOpenHelper的使用
    用Toast来增加调试效率的小技巧
    汇编语言-比较字符串
    正向代理和反向代理
    redis安装与配置
  • 原文地址:https://www.cnblogs.com/sowhat1412/p/12734504.html
Copyright © 2011-2022 走看看