用C++解决约瑟夫问题
来源:百度知道 编辑:UC知道 时间:2024/05/16 12:00:31
用C++实现约瑟夫问题。。。ORZ,我是菜鸟,各位大侠帮忙看看我这程序要怎么改啊??
//Node.h
#include<iostream>
typedef int Node_entry;
struct Node
{
//data menbers
Node_entry entry;
Node *next;
//constructors
Node();
Node(Node_entry item,Node *add_on=NULL);
};
//Node.cpp
#include "Node.h"
Node::Node()
{
next=NULL;
}
Node::Node(Node_entry item,Node *add_on)
{
entry=item;
next=add_on;
}
//main.cpp
#include<iostream>
#include "Node.h"
using namespace std;
void instructions();
void GetData(int& m,int& n);
void startGame(int& m,int& n);
int main()
{
int m,n;
instructions();
GetData(m,n);
startGame(m,n);
return 0;
}
//*************************************************************************************
void instructions()
{
cou
//Node.h
#include<iostream>
typedef int Node_entry;
struct Node
{
//data menbers
Node_entry entry;
Node *next;
//constructors
Node();
Node(Node_entry item,Node *add_on=NULL);
};
//Node.cpp
#include "Node.h"
Node::Node()
{
next=NULL;
}
Node::Node(Node_entry item,Node *add_on)
{
entry=item;
next=add_on;
}
//main.cpp
#include<iostream>
#include "Node.h"
using namespace std;
void instructions();
void GetData(int& m,int& n);
void startGame(int& m,int& n);
int main()
{
int m,n;
instructions();
GetData(m,n);
startGame(m,n);
return 0;
}
//*************************************************************************************
void instructions()
{
cou
错误都在startGame这个函数里。帮你改好了,细节看代码中的注释。
void startGame(int& m,int& n)
{
Node *head=new Node[m];
for(int i=0;i<m;i++){
head[i]=i+1;
// Node a=head[i];
head[i].next = head + i + 1; // <-- 指针的next要指向下一个元素
}
Node *tail=head+m-1;
tail->next =head;// <-- 最后一个指针(尾指针)的下一个执行头,才形成环
Node *cur=head;
Node *prev=NULL;
for(i=0;i<m-1;i++)
{
for(int j=0;j<n-1;j++)
{
prev=cur;
cur=cur->next;
}
cout<<"Delete person of number "<<cur->entry<<endl;
prev->next=cur->next;
//delete cur; <-- 不能释放一齐分配的内存中的一部分
cur=prev->next; // <-- 需要跳过那个出列的人
}
delete head; // <-- Node是整体分配的,也应该整体释放
}
呃…