Joseph ring problem (circular linked list)

WBOY
Release: 2016-07-25 09:01:35
Original
961 people have browsed it
php算法
  1. header("content-type:text/html;charset=utf-8");
  2. class Child{
  3. public $no;
  4. public $next=null;
  5. public function __construct($no){
  6. $this->no=$no;
  7. }
  8. }
  9. function addChild($n,&$first){ //$n是小孩个数,创建环形链表
  10. for($i=0;$i<$n;$i++){
  11. $child=new Child($i+1);
  12. if($i==0){
  13. $first=$child;
  14. $cur=$child;
  15. $cur->next=$cur;
  16. }else{
  17. $cur->next=$child;
  18. $child->next=$first;
  19. $cur=$cur->next;
  20. }
  21. }
  22. }
  23. function showHero($first){
  24. $cur=$first;
  25. while($cur->next!=$first){
  26. echo "
    小孩编号:".$cur->no;
  27. $cur=$cur->next;
  28. }
  29. echo "
    小孩编号:".$cur->no;
  30. }
  31. function countChild($first,$m,$k){
  32. $cur=$first;
  33. for($i=0;$i<$m-1;$i++){
  34. $cur=$cur->next;
  35. }
  36. $j=0;
  37. while($cur!=$cur->next){
  38. if($j==$k-2){
  39. echo "
    出列编号:".$cur->next->no;
  40. $cur->next=$cur->next->next;
  41. $cur=$cur->next;
  42. $j=0;
  43. }else{
  44. $cur=$cur->next;
  45. $j++;
  46. }
  47. }
  48. echo "
    最后出列编号:".$cur->no;
  49. }
  50. addChild(10,$first);
  51. showHero($first);
  52. echo "
    ";
  53. countChild($first,2,3); //第二个小孩开始数,数到三出列
  54. ?>
复制代码


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template