面試題六 C/C++面試祕笈 之約瑟夫問題的解答--程序員面試題

/**面試題12

 *約瑟夫問題的解答

 *1-N個人圍成一圈,從1M進行報數,每次報到M的人退出,一次循環,那麼最後一個人退出的是誰?

 *

 */

//結構體和函數聲明

typedef struct yuesefu

{

int data;

yuesefu *next;

}yuesefu;


//構造節點爲N的單向循環鏈表

yuesefu * yuesefu_create(int n)

{

yuesefu * pRet = NULL;

if (0 != n) {

int n_index = 1;

yuesefu *pNode = NULL;

pNode = new yuesefu[n];

if (NULL == pNode) {//申請內存失敗,返回NULL

return NULL;

}else{

memset(pNode, 0, n*sizeof(yuesefu));//初始化內存

}

pRet = pNode;

while (n_index < n) {//構建循環鏈表

pNode->data = n_index;//初始化鏈表的每個節點,從1N

pNode->next = pNode + 1;

pNode = pNode->next;

n_index++;

}

pNode->data = n;

pNode->next = pRet;

}

return pRet;

}



int main(int argc, const char * argv[]) {


//約瑟夫問題的解答

yuesefu * pList =NULL;

yuesefu * pIter =NULL;

int n =12;

int m =3;

/**構造單向循環鏈表*/

pList = yuesefu_create(n);

pIter = pList;

m %= n;

cout<<m<<endl;

while (pIter != pIter->next) {

int i=1;

/*取到第M-1個節點*/

for (;i < m-1; i++) {

pIter = pIter->next;

}

/*輸出第M個節點的值*/

printf("p->next = %d\n",pIter->next->data);

/*從鏈表中刪除第M個節點*/

pIter->next = pIter->next->next;

pIter = pIter->next;

}

printf("最後一個節點:%d\n",pIter->data);

/*釋放申請的內存*/

delete [] pList;

return 0;

}


C++程序實現:

int n,m,s=0;

cout<<"N";cin>>n;

cout<<"M";cin>>m;

for(int i=2;i<=n;i++)

{

s=(s+m)%i;

}

cout<<"最後一個是"<<s+1;



如果有任何問題,歡迎下方留言談論,或者加入QQ羣83459374交流

發佈了88 篇原創文章 · 獲贊 32 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章