使用php编写约瑟夫环问题


问题描述:
1、一群人围在一起坐成环状(如:n)
2、从某个编号开始报数(如:m)
3、数到某个数(如:k)的时候,此人出列,下一个人重新报数
4、一直循环,直到所有人出列,约瑟夫环结束
文件Node.class.php
<?
     class Node {
      public $num;   //节点计数
      public $next=null; //下一个节点
      public function __construct($no) {
       $this->num=$no;
      }
     }

文件Joseph.class.php
<?php

       require "Node.class.php";
       class Joseph {
         private $first;  //头节点
         private $last;  //尾节点
         public function __construst() {
          $this->first=null;
          $this->last=null;
         }

            public function addNode($n) { //$n 为节点的总数
            if(empty($n)) {
              echo "please input an interger";
              exit();
             }
             for($i=0; $i<$n; $i++) {    //生成n个节点,构成循环
              $node = new Node($i+1);
              if($i==0) {
               $this->first=$node;
               $this->first->next=$node;
               $this->last=$this->first;
              }else{
               $this->last->next=$node;
               $node->next=$this->first;
               $this->last=$node;
              }
             }
            }
            public function showNode() {
             $cur=$this->first;
             while($cur!=$this->last) {
              echo "<br/> 节点的编号为:".$cur->num;
      $cur=$cur->next;
             }
             //显示最后一个节点的编号
                 echo "<br/> 节点的编号为:".$cur->num;
             }

             public function countNode($m,$k) { //从第$m个节点开始数数,数$k个节点删除节点。
              
              for($i=1; $i<$m; $i++) {
               $this->first=$this->first->next;
               $this->last=$this->last->next;
              }
              while($this->first != $this->last){
               for($j=1; $j<$k; $j++) {
                $this->first=$this->first->next;
                $this->last=$this->last->next;
               }
               echo "<br/> 删去的编号为:".$this->first->num;
               $this->first=$this->first->next;
               $this->last->next=$this->first;
              }
              echo "<br/>最后一个编号为:".$this->last->num;
             }
       }
       $test= new Joseph();
       $test->addNode(5);
       $test->countNode(2,3);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值