后天急用,谢谢
////////// 头文件///////////////////
typedef struct member
{
int ID;//某个人的序号
int cipher;//密码
member *next;//下一个
}Person;
typedef struct
{
Person *head;//链表头
Person *tail;//链表尾
int lenth;//链表长
}List;
/////////////算法部分( cpp 文件)/////////////////////
//约瑟夫环
//添加链表元素
void AddMember(List &list,int ID,int cipher)
{
Person *per = (Person *)malloc(sizeof(Person));
per->ID = ID;
per->cipher = cipher;
//当链表为空时
if(list.lenth == 0)
{
list.head = per;
list.tail = per;
per->next = list.head;
}
else //当链表不空时
{
per->next = list.head;
list.tail->next = per;
list.tail = per;
}
list.lenth++;
}
//用来记录输出结果的数组 初始化
void InitArray(int lenth, int **array)
{
*array = (int *)malloc(lenth * sizeof(int));
}
//处理链表(排序)
void DoList(List list, int *array)
{
int N = list.lenth;//用于循环
int arrayCount = 0;//输出数组的下标
int cip;
Person *person = list.head;
cip = person->cipher;
while(N > 0)
{
for(int i = 1; i < cip; i++)//找出下一个出列的人
person = person->next;
Person *p = person->next;
cip = p->cipher;
array[arrayCount] = p->ID;
arrayCount++;
person->next = p->next;
free(p);
N--;
}
}
////////////主函数部分 ( cpp 文件)/////////////////////
#include <iostream.h>
#include <malloc.h>
#include <stdlib.h>
#include "test2.h"
#include "algo2.cpp"
void main()
{
int max, n;
int cipher;
List list;
char loop;//循环的标志
do
{
cout<<"*************** 约瑟夫环问题 ****************"<<endl<<endl;
do
{
cout<<"输入密码的最大值: ";
cin>>max;
cout<<endl<<"输入人数: ";
cin>>n;
if(max <= 0 || n <= 0)
cout<<"你所输入的数不能小于 1,请重新输入"<<endl;
}
while(max <= 0 || n <= 0);
list.lenth = 0;
for(int i = 1; i <= n; i++)
{
cout<<"输入第 "<<i<<" 个人的密码(必须大于0): ";
do
{
cin>>cipher;
if(cipher > max)
cout<<"你所输入的数大于密码的最大值,请从新输入:"<<endl;
if(cipher <= 0)
cout<<"你所输入的数小于 1,请从新输入:"<<endl;
}
while(cipher > max || cipher <= 0);
AddMember(list, i, cipher);//添加成员
}
int *array;
InitArray(n, &array);//数组初始化
DoList(list, array);//按顺序删除成员
cout<<endl<<"************* 出列顺序为 ***************"<<endl;
for(i = 1; i <= n; i++)//输出出列顺序
{
if(i%20 == 0)
cout<<endl;
cout<<array[i-1]<<" ";
}
cout<<endl<<"是否要继续?(Y / N)"<<endl;
cin>>loop;
system("cls");//清屏幕
}
while(loop == 'Y' || loop == 'y');
}
刚好做了一个, 不是很规范, 不介意就拿去.