生活随笔
收集整理的這篇文章主要介紹了
约瑟夫环问题---循环单链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
約瑟夫環問題是比較經典的問題,原來做的題目是依次輸出數字,而原來的循環鏈表結構不改變,今天遇到一道題是要求按照順序重新組成一個循環單鏈表。
題目:一些人圍坐一圈報數,形成一個循環單鏈表,當報數是m或m的倍數時出將節點從單鏈表中刪除,重新加入新的循環單鏈表,最后形成一個新的循環單鏈表。
?
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 。。。
結果:5 10 6 2 9 8 1 4 7 3 5 10 6 2 。。。
轉載于:https://blog.51cto.com/buptdtt/989174
總結
以上是生活随笔為你收集整理的约瑟夫环问题---循环单链表的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。