主题:约瑟夫环
#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;
}
期望大家指正程序中的错误,互相学习!一般数据可以使用
#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;
}
期望大家指正程序中的错误,互相学习!一般数据可以使用