约瑟夫环问题的原来描述为:设有编号为1,2,……,n的n(n>0)个人围成一个圈,从第1个人开始按顺时针方向自1开始顺序报数,报到m时停止报数。报m的人出列。从他在顺时针方向上的下一个人开始重新从1报数,如此下去,直至所有人全部出列为止。试设计一个程序求出出列顺序。
通过输入:n,m
输出:出列序列
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}NODE,*PNODE;
int n;
PNODE creat_list()
{
PNODE head=new Node;
int val;
cout<<"the number of the list is:"<<endl;
cin>>n;
cout<<"input the element of the list:"<<endl;
cin>>val;
head->data =val;
PNODE temp=head;
temp->next =NULL;
for(int i=2;i<=n;i++) //输入1 2 3 4 5 6.。。。。n;
{
PNODE pnew=new Node;
cin>>val;
pnew->data =val;
temp->next =pnew;
temp=pnew;
}
temp->next =head; //不要忘了这步,构成循环链表
return head;
}
void delete_node(PNODE head,int n,int m)
{
int count=0;
PNODE p=head;
PNODE s,q;
cout<<"the list of output is:"<<endl;
while(count<n)
{
int j=m; //必要性,每次循环m都不变
while(j>1)
{
s=p;
p=p->next;
j--;
}
cout<<p->data<<" ";
q=p;
s->next =p->next;
p=p->next;
delete(q);
count++; //当删除了n个元素时,
}
}
int main()
{
PNODE head=creat_list();
int m;
cout<<"input the position of deleted number:"<<endl;
cin>>m;
delete_node(head,n,m);
return 0;
}
题目改为:从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从第k开始报数,数到m的那个人出列;依次规律重复下去,直到所有的数都出列。
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}NODE,*PNODE;
int n;
PNODE creat_list()
{
PNODE head=new Node;
int val;
cout<<"the number of the list is:"<<endl;
cin>>n;
cout<<"input the element of the list:"<<endl;
cin>>val;
head->data =val;
PNODE temp=head;
temp->next =NULL;
for(int i=2;i<=n;i++)
{
PNODE pnew=new Node;
cin>>val;
pnew->data =val;
temp->next =pnew;
temp=pnew;
}
temp->next =head; //不要忘了这步,构成循环链表
return head;
}
void delete_node(PNODE head,int n,int k,int m)
{
int count=0;
PNODE p=head;
int i=k; //增加部分
while(i>1)
{
p=p->next ; //找到第k个数,开始报数
i--;
}
PNODE s,q;
cout<<"the list of output is:"<<endl;
while(count<n)
{
int j=m-k; //必要性,每次循环m都不变
while(j--) //变化
{
s=p;
p=p->next;
}
cout<<p->data<<" ";
q=p;
s->next =p->next;
p=p->next;
delete(q);
count++; //当删除了n个元素时,
}
}
int main()
{
PNODE head=creat_list();
int m,k;
cout<<"k=";
cin>>k;
cout<<"m=";
cin>>m;
delete_node(head,n,k,m);
return 0;
}