首發:http://www.5dkx.com/arch/65.html
前天筆試有個約瑟夫環的問題,怪不得人家沒通知我面試,原來我的約瑟夫環做的確實有問題,昨天晚上又重新做了下,下面上原始碼:
/*
file:osephu.cpp
author:www.5dkx.com
*/
#include <iostream>
using namespace std;
typedef struct Node{
int sort;
struct Node *next;
}Link,*List;
int Init(List *p); //初始化雙鏈表
int Insert(List *p,int key); //插入節點
void Print(List p); //列印雙鏈表
void CreateOsep(List p,int n); //初始化約瑟夫環
void osehup(List p,int m,int len,List Re); //計算約瑟夫環出列順序,並存放在Re鏈表中
int main()
{
int m,n;
List p,Re;
Init(&p);
Init(&Re);
cout<<"輸入環大小: ";
cin>>n;
cout<<"輸入地幾個人出列: ";
cin>>m;
CreateOsep(p,n);
cout<<"輸入為: "<<endl;
Print(p);
osehup(p,m,n,Re);
cout<<"出隊順序為:"<<endl;
Print(Re);
return 1;
}
//初始化
int Init(List *p)
{
*p = (List)malloc(sizeof(Link));
if(!(*p))
{
cout<<"初始化失敗!"<<endl;
return 0;
}
else
{
(*p)->next=*p;
//(*p)->sort=1;
}
return 1;
}
//插入節點
int Insert(List *p,int key)
{
List tmp = (List)malloc(sizeof(Link));
if(!tmp)
{
cout<<"建立節點失敗!"<<endl;
return 0;
}
else
{
tmp->sort=key;
tmp->next=(*p)->next;
(*p)->next=tmp;
*p=tmp;
}
return 1;
}
//建立約瑟夫環
void CreateOsep(List p,int n)
{
List tmp=p;
tmp->sort=1;
for(int i=2;i<=n;i++)
Insert(&tmp,i);
}
//約瑟夫環演算法
void osehup(List p,int m,int len,List Re)
{
int count=0;
int allc=0;
List tmp1=p;
List tmp2=Re;
List temp;
while(allc<len)
{
count++;
if(count == m)
{
temp = tmp1->next;
if(allc==0) //如果是第一次出列
tmp2->sort=temp->sort;
else
Insert(&tmp2,temp->sort);
tmp1->next=tmp1->next->next;
// cout<<temp->sort<<" ";
free(temp);
temp=NULL;
allc++;
count=0;
}
else
{
tmp1=tmp1->next;
}
}
cout<<endl;
}
//列印鏈表
void Print(List p)
{
List tmp=p->next;
cout<<p->sort<<" ";
while(tmp!=p)
{
cout<<tmp->sort<<" ";
tmp=tmp->next;
}
cout<<endl;
}
運行後效果為:
輸入環大小: 5
輸入地幾個人出列: 6
輸入為:
1 2 3 4 5
出隊順序為:
2 4 3 1 5
Press any key to continue
非特別說明均為原創文章如轉載,請註明:轉載自 5D開心部落格 [ http://www.5DKX.com/ ]