约瑟夫环问题怎么解决啊?请用C语言写代码,谢谢!

2024年11月29日 22:33
有2个网友回答
网友(1):

#include"MyNode.h" //文件1

Node::Node( )
{
next = NULL;
}

Node::Node(Node_entry item, Node *add_on)
{
entry = item;
next = add_on;
}
--------------
#include //文件2
typedef int Node_entry;

struct Node {
// data members
Node_entry entry;
Node *next;
// constructors
Node( );
Node(Node_entry item, Node *add_on = NULL);
};
---------------------
#include"MyNode.h" //主程序
#include
void main(){
int n,m;
Node *p=NULL, *p_head=NULL ,*p_tmp=NULL;
cout<<"This is a YSF(n,m) problem."<//n people, m count, both n and m should >= 1
do{
cout<<"Please input the n(n>1).";
cin>>n;
}while(n<1);
do{
cout<<"Please input the m(m>1).";
cin>>m;
}while(m<1);

//construct the circular link structure
for(int i=n;i>=1;i--){
p_head = new Node(i,p);
p=p_head;
}

//get to the tail, which is n.
while(p->next)p=p->next;
//connect to a circular
p->next=p_head;

//go with the circular
for(i=1;i for(int k=1;knext;
p_tmp=p->next;
p->next=p_tmp->next;
cout<entry;
delete p_tmp;
}
//Print the left element
cout<entry<}

我这个学期也搞数据结构

程序可以运行的

网友(2):

#include"MyNode.h"
//文件1
Node::Node(
)
{
next
=
NULL;
}
Node::Node(Node_entry
item,
Node
*add_on)
{
entry
=
item;
next
=
add_on;
}
--------------
#include
//文件2
typedef
int
Node_entry;
struct
Node
{
//
data
members
Node_entry
entry;
Node
*next;
//
constructors
Node(
);
Node(Node_entry
item,
Node
*add_on
=
NULL);
};
---------------------
#include"MyNode.h"
//主程序
#include
void
main(){
int
n,m;
Node
*p=NULL,
*p_head=NULL
,*p_tmp=NULL;
cout<<"This
is
a
YSF(n,m)
problem."<//n
people,
m
count,
both
n
and
m
should
>=
1
do{
cout<<"Please
input
the
n(n>1).";
cin>>n;
}while(n<1);
do{
cout<<"Please
input
the
m(m>1).";
cin>>m;
}while(m<1);
//construct
the
circular
link
structure
for(int
i=n;i>=1;i--){
p_head
=
new
Node(i,p);
p=p_head;
}
//get
to
the
tail,
which
is
n.
while(p->next)p=p->next;
//connect
to
a
circular
p->next=p_head;
//go
with
the
circular
for(i=1;i//do
n-1
times
to
get
rid
of
n-1
elements.
for(int
k=1;knext;
p_tmp=p->next;
p->next=p_tmp->next;
cout<rid
of:"<entry;
delete
p_tmp;
}
//Print
the
left
element
cout<left
element
is:"<entry<}
我这个学期也搞数据结构
程序可以运行的