头文件EnforceJoseph.h
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int password;
int peopleOfNumber;
Node *next;
};
Node *first;
Node *last;
//用于遍历约瑟夫环的函数,传入的形参第一个为首地址,第二个是初始上限值
bool Enforce(Node *node, int m)
{
Node *p = node;
Node *q = p;
if ((*p).next == p) return true;
int i = 0;
for (; i < m; i++)
{
p = (*p).next;
if (i == 0) continue;
q = (*q).next;
}
m = (*p).password;
printf("出列的人为:%d", (*p).peopleOfNumber);
(*q).next = (*p).next;
free(p);
Enforce((*q).next, m);
return true;
}
//建立一个只有一个结点的链表
void setup()
{
first =(Node *) malloc(sizeof(Node));
last = first;
(*last).next = first;
}
//向链表添加数据
void add(int password, int numberOfPeople)
{
Node *p;
if (last == first)
{
p = first;
}
else p = (Node *)malloc(sizeof(Node));
(*p).password = password;
(*p).peopleOfNumber= numberOfPeople;
(*p).next = first;
last = p;
}
bool checkIfNull()
{
Node *q = (*first).next;
if (((*first).next == first) || (*q).next == first)
return false;
else return true;
}
void begin(int m)
{
Enforce(first, m);
}
下面是包含该头文件的,main函数所在的文件"源.cpp":
#include<stdio.h>
#include<string.h>
#include "EnforceJoseph.h"
int m;
int pass;
int num;
char yOrN[3];
int main()
{
void start();
start();
system("PAUSE");
}
void start()
{
void input(int type);
void check(int type);
setup();
input(1);
input(2);
input(3);
check(4);
begin(m);
}
void input(int type)
{
void check(int type);
switch (type)
{
case 1:
printf("请输入m的值\n");
scanf_s("%d", &m);
check(1);
break;
case 2:
printf("请输入密码和位置");
scanf_s("%d %d", &pass, &num);
check(2);
add(pass,num);
break;
case 3:
printf("你是否要继续输入?请输入yes或no\n");
scanf_s("%s", yOrN);
check(3);
}
}
void check(int type)
{
switch (type)
{
case 1:
if (m != (int)m)
{
printf("你输入的m值不合要求,请重新输入\n");
input(1);
}
case 2:
if (pass > m)
{
printf("你输入的密码不合要求,重新输入\n");
input(2);
}
case 3:
if ((strcmp(yOrN, "yes") != 0) && (strcmp(yOrN, "no") != 0))
{
printf("请输入yes或no\n");
input(3);
}
else input(2);
break;
case 4:
if (!checkIfNull())
{
printf("你建立的链表不合法,请重新建立");
input(2);
}
break;
}
}
求解决方法