Home  >  Article  >  Backend Development  >  约瑟夫环问题(环形链表)

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

WBOY
WBOYOriginal
2016-07-25 09:01:35854browse
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 $child=new Child($i+1);
  11. if($i==0){
  12. $first=$child;
  13. $cur=$child;
  14. $cur->next=$cur;
  15. }else{
  16. $cur->next=$child;
  17. $child->next=$first;
  18. $cur=$cur->next;
  19. }
  20. }
  21. }
  22. function showHero($first){
  23. $cur=$first;
  24. while($cur->next!=$first){
  25. echo "
    小孩编号:".$cur->no;
  26. $cur=$cur->next;
  27. }
  28. echo "
    小孩编号:".$cur->no;
  29. }
  30. function countChild($first,$m,$k){
  31. $cur=$first;
  32. for($i=0;$i $cur=$cur->next;
  33. }
  34. $j=0;
  35. while($cur!=$cur->next){
  36. if($j==$k-2){
  37. echo "
    出列编号:".$cur->next->no;
  38. $cur->next=$cur->next->next;
  39. $cur=$cur->next;
  40. $j=0;
  41. }else{
  42. $cur=$cur->next;
  43. $j++;
  44. }
  45. }
  46. echo "
    最后出列编号:".$cur->no;
  47. }
  48. addChild(10,$first);
  49. showHero($first);
  50. echo "
    ";
  51. countChild($first,2,3); //第二个小孩开始数,数到三出列
  52. ?>
复制代码


Statement:
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