Posted on 2006-05-13 16:07
SmallTalk 阅读(3678)
评论(1) 编辑 收藏 引用 所属分类:
C++小程序
//Jose.cpp----使用单向循环链表实现约瑟夫问题
//问题描述:n个人手拉手排成一个环,从第一个人开始数,每数到第m个人,第m个人出列,从下一人重新计数重新数,求全部出列后他们的出列顺序
#include <iostream.h>
struct jose
{
int data;
int no;
struct jose * next;
};
int main()
{
struct jose *head,*p_curent,*p_find;
int n,m;
cout << "Please enter the total of numbers (n):";
cin >> n;
cout << "Please enter the counter number (m):";
cin >> m;
//初始化链表
head=p_curent=new jose;//标记首表元地址,即头指针
head->no=1;
cout << "Please enter the first number :";
cin >>head->data;
//形成其余的n-1表元
cout << "Please enter last numbers :"<<endl;
for (int i=2;i<=n;i++)
{
p_curent->next=new jose;
p_curent=p_curent->next;
cin >> p_curent->data;
p_curent->no=i;
}//end for
p_curent->next=head;//尾指针指向头指针,形成环,到这完成初始化链表
//开始查询,第M个人出列,并输出
cout << "Now : The numbers of who will quit the cycle in turn are:"<<endl;
while (n)//全部出列后结束循环
{
//掠过m-1个表元
for (int j=1;j<m;j++)
p_curent=p_curent->next;//end for
//找到第M个人
p_find=p_curent->next;
//从表中删除第m个人,并输出第m个人
p_curent->next=p_find->next;
cout << p_find->data<<endl;
//释放第m个表元占用的空间
delete p_find;
n--;
}
//end while
return 0;
}