Php uses a circular linked list to solve the Joseph Ring problem. Joseph's example

Source: Internet
Author: User

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

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.