问题:n个人围成一个环,从第i个开始,由1至interval不断报数,凡报到interval的出列,直到环空为止。
#include <iostream>
#include <string>
using namespace std;
//结构体
struct jonsephus
{
int code;//数字
jonsephus *next;//next指针
};
void jonsInt(jonsephus *&head,int n)
{
jonsephus *g;//g为跟踪指针
g = head = new jonsephus;//新结点
for (int j = 1; j <= n; j++)
{
g->code = j;
if (j == n) g->next = head;//最后一个结点的next指针指向头指针 形成环状
else g->next = new jonsephus;//新结点插入链表
g = g->next;//跟踪指针指向新结点
}
}
void showJ(jonsephus *head)
{
cout << "Now include:" << endl;
jonsephus *pp = head;//跟踪指针pp
do
{
cout << pp->code << ' ';
pp = pp->next;//移动跟踪指针位置
}
while (head != pp);//遍历 当head指针等于pp 表示指针移到了头指针位置
cout << endl;
}
void standUp(jonsephus *&head,int n,int i,int interval)
{
jonsephus *q = NULL,*p = NULL;//定义两个跟踪指针
int c;//当前计数
jonsInt(head, n);
showJ(head);//检查初始化是否成功
p = q = head;//先设定pq均为头指针
while (p->next != head)//遍历得到指向头指针的指针作为p
{
p = p->next;
}
for (c = 1;c < i; c++)//循环移位等到从第i位开始数数
{
p = p->next;
q = p->next;
}
while (p != q)//若果p指针的next指向它自身 表明剩下最后一个对象
{
for ( c = 1; c < interval; c++)//每次循环interval-1次挪动指针即可,再下面代码会挪动一次指针
{
p = p->next;
q = p->next;
}
cout << q->code << " is stand up!" << endl;//输出的是q指针的值 下面要释放q指针指向的内存空间
p->next = q->next;//p指针的next指针指向q指针的next指针 这三句代码相当于挪动了一次指针
delete q;//释放q指针指向的内存空间
q = p->next;//q指针指向p的next指针
}
cout << q->code << " is stand up!" << endl;//输出最后一个
}
void main()
{
int n, i, interval;
cout << "How many persons?" << endl;
cin >> n;//输入多少人
cout << "Start with which person?" << endl;
cin >> i;//输入哪个人开始报数
cout << "Which number will stand up?" << endl;
cin >> interval;//输入数到第几则出列
jonsephus *head = NULL;//定义头指针
standUp(head, n, i, interval);//调用函数
getchar();
getchar();
}