问题描述:
1、一群人围在一起坐成环状(如:n)
2、从某个编号开始报数(如:m)
3、数到某个数(如:k)的时候,此人出列,下一个人重新报数
4、一直循环,直到所有人出列,约瑟夫环结束
文件Node.class.php
<?
class Node {
public $num; //节点计数
public $next=null; //下一个节点
public $next=null; //下一个节点
public function __construct($no) {
$this->num=$no;
}
}
}
}
文件Joseph.class.php
<?php
require "Node.class.php";
class Joseph {
private $first; //头节点
private $last; //尾节点
private $last; //尾节点
public function __construst() {
$this->first=null;
$this->last=null;
$this->last=null;
}
public function addNode($n) { //$n 为节点的总数
if(empty($n)) {
echo "please input an interger";
exit();
}
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;
$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;
$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;
}
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;
}
$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;
}
$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);
$test->addNode(5);
$test->countNode(2,3);