Joseph ring (circular linked list)
Php algorithm
- Header ("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 children. create a circular linked list
- For ($ I = 0; $ I <$ n; $ I ++ ){
- $ Child = new Child ($ I + 1 );
- If ($ I = 0 ){
- $ First = $ child;
- $ Cur = $ child;
- $ Cur-> next = $ cur;
- } Else {
- $ Cur-> next = $ child;
- $ Child-> next = $ first;
- $ Cur = $ cur-> next;
- }
- }
- }
- Function showHero ($ first ){
- $ Cur = $ first;
- While ($ cur-> next! = $ First ){
- Echo"
Kid ID: ". $ cur-> no;
- $ Cur = $ cur-> next;
- }
- Echo"
Kid ID: ". $ cur-> no;
- }
- Function countChild ($ first, $ m, $ k ){
- $ Cur = $ first;
- For ($ I = 0; $ I <M-1; $ I ++ ){
- $ Cur = $ cur-> next;
- }
- $ J = 0;
- While ($ cur! = $ Cur-> next ){
- If ($ j = $ K-2 ){
- Echo"
Column number: ". $ cur-> next-> no;
- $ Cur-> next = $ cur-> next;
- $ Cur = $ cur-> next;
- $ J = 0;
- } Else {
- $ Cur = $ cur-> next;
- $ J ++;
- }
- }
- Echo"
Last column number: ". $ cur-> no;
- }
- AddChild (10, $ first );
- ShowHero ($ first );
- Echo" ";
- CountChild ($ first, 2, 3); // count the number of the second child to three
- ?>
|