Posted on 2006-05-13 16:07
SmallTalk 閱讀(3688)
評論(1) 編輯 收藏 引用 所屬分類:
C++小程序
//Jose.cpp----使用單向循環(huán)鏈表實(shí)現(xiàn)約瑟夫問題
//問題描述:n個(gè)人手拉手排成一個(gè)環(huán),從第一個(gè)人開始數(shù),每數(shù)到第m個(gè)人,第m個(gè)人出列,從下一人重新計(jì)數(shù)重新數(shù),求全部出列后他們的出列順序
#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;//標(biāo)記首表元地址,即頭指針
?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;//尾指針指向頭指針,形成環(huán),到這完成初始化鏈表
?//開始查詢,第M個(gè)人出列,并輸出
?cout << "Now : The? numbers of who will quit the cycle in turn are:"<<endl;
?while (n)//全部出列后結(jié)束循環(huán)
?{
??//掠過m-1個(gè)表元
??for (int j=1;j<m;j++)
???p_curent=p_curent->next;//end?for
??//找到第M個(gè)人
??p_find=p_curent->next;
??//從表中刪除第m個(gè)人,并輸出第m個(gè)人
??p_curent->next=p_find->next;
??cout << p_find->data<<endl;
??//釋放第m個(gè)表元占用的空間
??delete p_find;
??n--;
?}
?//end while
?
?return 0;
}