约瑟夫环问题(环形链表)

原创
2016-07-25 09:01:35 637浏览
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. ?>
复制代码


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:PHP遍历指定目录下所有文件函数,可指定文件类型 下一条:php+shell检测文件类型

相关文章

查看更多