回 帖 发 新 帖 刷新版面

主题:约瑟夫环

#include "iostream.h"
#define NULL 0
struct Node{
    int NO;
    int password;
    struct Node *next;
};
struct Node *CreateJosepherCircle()
{
    struct Node *p;
    struct Node *q;
    struct Node *head;
    int num=1;
    p=new struct Node;
    p->NO=num;
    cin>>p->password;
    p->next=p;
    head=p;
    while(p->password!=-1)
    {
        q=p;
        p=new struct Node;
        p->NO=++num;
        cin>>p->password;
        q->next=p;
        p->next=head;
    }
    q->next=head;
    delete(p);
    return(head);
}
void OutQueenOrder(struct Node *head,int start)
//根据以head为头结点的循环链表的关键字及密码给出其输出顺序
{
    struct Node *p;
    struct Node *q;
    int password;
    int sts;
    sts=start;
    p=head;
    while(sts!=1)
    {
        q=p;
        p=p->next;
        sts=sts-1;
    }
    while(p!=NULL)
    {
        cout<<p->NO<<"   ";
        if(p->next==p)p=NULL;
        else
        {
            password=p->password;
            q->next=p->next;
            delete(p);
            p=q->next;
            while(password!=1)
            {
                q=p;
                p=p->next;
                password=password-1;
            }
        }
    }
}
void main()
{
    struct Node *head;
    int start;
    cout<<"请给出Josepher环的密码,以-1作为输入结束的标志:"<<endl;
    head=CreateJosepherCircle();
    cout<<"请输入起始号:"<<endl;
    cin>>start;
    cout<<"Josepher环的输出顺序为:"<<endl;
    OutQueenOrder(head,start);
    cout<<endl;
}

期望大家指正程序中的错误,互相学习!一般数据可以使用

回复列表 (共4个回复)

沙发

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    int n, i=0, m, p;
    scanf("%d%d", &n, &m);
    while (++i <= n ){
        p=i*m;
        while( p>n )
            p = p - n + (p-n-1)/(m-1);
           printf("%d\n", p);
    }    
    system("PAUSE");    
}


这个也是约瑟夫环
效率高的多

板凳

我知道了,你采用的不是链表,而是数组,这样就可以直接定位,就像哈西表一样,而无需顺序查找了,这样效率当然高啦,好样的!支持一下!

3 楼

第一位楼主以程序审美的角度写得非常好,值得赞赏!!!
第二位楼主以程序简洁和效率上写得也非常好,也值得称道!!!
其实大家各抒己见也非常好啊,感谢两位的努力!!!

4 楼

呵呵,客气客气!

我来回复

您尚未登录,请登录后再回复。点此登录或注册