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

    关注公众号 海量干货等你
  • 相关阅读:
    markown 画图
    C++ 结构体指针
    C++指针详解
    C++ 中类对象与类指针的区别
    Java面向对象㈠ -- 封装
    path和classpath
    "System.Web" 中不存在类型或命名空间
    ASP.NET 后台不识别ASPX中的控件
    asp.net中的<%%>形式的详细用法实例讲解
    ASP.NET前台JS与后台CS函数如何互相调用
  • 原文地址:https://www.cnblogs.com/sowhat1412/p/12734504.html
Copyright © 2011-2022 走看看