Solve Joseph's problem through a circular linked list-PHP source code

Source: Internet
Author: User
Php code for solving the Joseph problem using a ring linked list:

// Circular linked list/* solve the Joseph problem and set the number of persons starting from 1-N according to the number of individuals starting from k to report the number from 1, and report the number to the person from m. His next digit starts counting from 1, and the person counting to M goes out again, and so on until all the people come out of the column and find the column order, and the last column number */header ("content-type: text/html; charset = utf-8"); class Child {public $ no; public $ next = null; public function _ construct ($ no) {$ this-> no = $ no ;}} function addChild (& $ first, $ n) {$ cur = null; for ($ I = 0; $ I <= $ n-1; $ I ++) {$ child = new child ($ I + 1); if ($ I = 0) {$ first = $ child; $ first-> next = $ child; $ cur = $ first;} else {$ cur-> next = $ child; $ child-> next = $ fi Rst; $ cur = $ cur-> next ;}} function showChild ($ first) {$ cur = $ first; while ($ cur-> next! = $ First) {echo $ cur-> no; $ cur = $ cur-> next;} echo $ cur-> no;} function countChild ($ first, $ m, $ k) {$ tail = $ first; // consider starting from the first few children for ($ I = 0; $ I <M-1; $ I ++) {$ tail = $ tail-> next;} while ($ tail-> next! = $ Tail) // remove to the linked list only one element until {for ($ I = 0; $ I <$ K-1; $ I ++) {$ cur = $ tail; // record his previous position $ tail = $ tail-> next;} echo 'column output '. $ tail-> no; $ cur-> next = $ tail-> next; $ tail = $ tail-> next;} echo '123 '. $ tail-> no;} addChild ($ first, 10); showChild ($ first); echo"
 "; CountChild ($ first, 2, 3); // count the number of the second child to three

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.