約瑟夫環C語言實現原始碼

來源:互聯網
上載者:User

首發: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/ ]

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.