生活随笔
收集整理的這篇文章主要介紹了
约瑟夫环问题---循环单链表
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
約瑟夫環(huán)問題是比較經(jīng)典的問題,原來做的題目是依次輸出數(shù)字,而原來的循環(huán)鏈表結(jié)構(gòu)不改變,今天遇到一道題是要求按照順序重新組成一個(gè)循環(huán)單鏈表。
題目:一些人圍坐一圈報(bào)數(shù),形成一個(gè)循環(huán)單鏈表,當(dāng)報(bào)數(shù)是m或m的倍數(shù)時(shí)出將節(jié)點(diǎn)從單鏈表中刪除,重新加入新的循環(huán)單鏈表,最后形成一個(gè)新的循環(huán)單鏈表。
?
struct?Node ?{ ?????int?data; ?????Node?*next; ?}; ??void?circle(Node**?head,int?m) ?{ ?????Node*?tmp1=*head; ?????Node?*tmp2=(*head)->next; ?????int?cnt=1; ?????while(1) ?????{ ?????????cnt++; ?????????if(cnt%m==0) ?????????{ ?????????????*head=tmp2; ?????????????tmp1->next=tmp2->next; ?????????????tmp2=tmp2->next; ?????????????break; ?????????} ?????????else?????????{ ?????????????tmp1=tmp1->next; ?????????????tmp2=tmp2->next; ??????????} ?????} ?????Node?*tmp3=*head; ?????while(tmp1!=tmp2) ?????{ ?????????cnt++; ?????????if(cnt%m==0) ?????????{ ?????????????tmp3->next=tmp2; ?????????????tmp3=tmp3->next; ?????????????tmp1->next=tmp2->next; ?????????????tmp2=tmp2->next; ????????? ?????????} ?????????else?????????{ ?????????????tmp1=tmp1->next; ?????????????tmp2=tmp2->next; ??????????} ?????} ?????tmp3->next=tmp2; ?????tmp2->next=*head; ??} ???int?main(?int?argc,?char**?argv?) ?{ ????? ?????Node?a[10]; ?????for(int?i=0;i<9;i++) ?????{ ?????????a[i].data=i+1; ?????????a[i].next=&a[i+1]; ?????} ?????a[9].data=10; ?????a[9].next=&a[0]; ?????Node?*aa=&a[0]; ?????Node?**aaa=&aa; ?????circle(aaa,5); ?????return?-1; ?}? 原始:1 2 3 4 5 6 7 8 9 10 1 2 。。。
結(jié)果:5 10 6 2 9 8 1 4 7 3 5 10 6 2 。。。
轉(zhuǎn)載于:https://blog.51cto.com/buptdtt/989174
總結(jié)
以上是生活随笔為你收集整理的约瑟夫环问题---循环单链表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。