Php uses a circular linked list to solve the Joseph Ring problem. Joseph's example
This article describes how php solves the Joseph Ring problem based on the ring linked list. We will share this with you for your reference. The details are as follows:
Let's repeat the Joseph's ring problem: N people are in a circle, starting from the first to report the number, M will be killed, and the last one will be killed. For example, N = 6, M = 5, and the order of being killed is: 5, 4, 6, 2, 3, 1.
The method for solving the Joseph ring by associating arrays is introduced. The method for solving the Joseph ring by using a ring linked list is as follows:
<? Phpheader ("content-type: text/html; charset = UTF-8"); class Child {public $ no; public $ next = null; public function _ construct ($ no) {$ this-> no = $ no;} function addChild ($ n, & $ first) {// $ n indicates the number of persons, create a circular linked list for ($ I = 0; $ I <$ n; $ I ++) {$ child = new Child ($ I + 1 ); if ($ I = 0) {$ first = $ child; $ cur-> next = $ cur ;} else {$ cur-> next = $ child; $ child-> next = $ first; $ cur = $ cur-> next ;}} function showHero ($ first) {$ cur = $ first; whil E ($ cur-> next! = $ First) {echo "<br/> person ID :". $ cur-> no; $ cur = $ cur-> next;} echo "<br/> person ID :". $ cur-> no;} function countChild ($ first, $ m, $ k) {$ cur = $ first; for ($ I = 0; $ I <$ s-1; $ I ++) {$ cur = $ cur-> next;} $ j = 0; while ($ cur! = $ Cur-> next) {if ($ j = $ K-2) {echo "<br/> column number :". $ cur-> next-> no; $ cur-> next = $ cur-> next; $ cur = $ cur-> next; $ j = 0 ;} else {$ cur = $ cur-> next; $ j ++ ;}} echo "<br/> last column number :". $ cur-> no;} addChild (10, $ first); showHero ($ first); echo "
Running result:
Person ID: 1 person ID: 2 person ID: 3 person ID: 4 person ID: 5 person ID: 6 person ID: 7 person ID: 8: 9: 10: 4: 4: 7: 10: 3: 8: 2: 9 column number: 6 column number: 1 last column number: 5