生活随笔
收集整理的這篇文章主要介紹了
约瑟夫环之循环链表实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
約瑟夫環是一個數學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數,數到m的那個人出列;他的下一個人又從1開
始報數,數到m的那個人又出列;依此規律重復下去,直到圓桌周圍的人全部出列。現編寫循環鏈表程序來實現約瑟夫環問題并輸出每次出列的結果~
用循環鏈表模擬此過程即可:1、建表;2、模擬出列規則。
下面還是老套路,直接貼上源碼+注釋~
Code:
[cpp]?view plaincopyprint?
#include<iostream>?? using?namespace?std;?? ?? typedef?struct?List?? {?? ????int?data;?? ????struct?List?*next;?? }List,?*Lnode;?? ?? void?Josephus(int?n,?int?k,?int?m)?? {?? ????Lnode?first,?now,?pre,?temp;?? ?????? ????first?=?(Lnode)malloc(sizeof(List));?? ????first->data?=?1;?? ????first->next?=?first;?? ????now?=?first;?? ?????? ????for(int?iFirst?=?2;?iFirst?<=?n;?iFirst++)?? ????{?? ????????temp?=?(Lnode)malloc(sizeof(List));?? ????????temp->data?=?iFirst;??? ?????????? ????????temp->next?=?now->next;????????? ????????now->next?=?temp;?????? ????????now?=?temp;??????????? ????}?? ?????? ????now?=?now->next;?? ?????? ????while(--k)??? ????{?? ????????pre?=?now;?? ????????now?=?now->next;?? ????}?? ?????? ????printf("The?Line?is?:?");?? ????while(n--)?? ????{?? ????????for(int?j?=?1;?j?<?m;?j++)?? ????????{?? ????????????pre?=?now;?? ????????????now?=?now->next;?? ????????}?? ?????????? ????????pre->next?=?now->next;?? ????????if(now->next?==?now)?printf("%d\n\n",?now->data);?? ????????else?printf("%d->",?now->data);?? ????????first?=?now->next;????? ????????free(now);???? ????????now?=?first;?????? ????}?? }?? ?? int?main()?? {?? ????Josephus(9,?1,?5);?? ????return?0;?? }??
總結
以上是生活随笔為你收集整理的约瑟夫环之循环链表实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。