<?php
// Josephu Quession
class Person {
public $no;
public $next = NULL;
public function __construct($no) {
$this->no = $no;
}
}
class RoundList {
public $head = NULL;
public $tail = NULL;
public function __construct($n) {
$this->create($n);
}
private function create($n) {
for ($i = 1; $i <= $n; $i += 1) {
if ($i == 1) {
$this->head = $this->tail = new Person($i);
} else {
$this->tail->next = new Person($i);
$this->tail = $this->tail->next;
}
}
$this->tail->next = $this->head;
}
function delete($p) {
$curr = $this->head;
$flag = TRUE;
while ($curr->next != $p) {
$curr = $curr->next;
if ($curr == $this->head) {
$flag = FALSE;
break;
}
}
if ($flag) {
// 删除节点是头节点
if ($curr == $this->tail) {
$this->head = $this->head->next;
$curr->next = $this->head;
}
// 删除节点是尾节点
else if ($curr->next == $this->tail) {
$curr->next = $this->tail->next;
$this->tail = $curr;
}
// 删除节点是中间节点
else {
$curr->next = $curr->next->next;
}
}
// 返回删除节点的next节点
return $curr->next;
}
}
// $n个人围坐一圈,第$k个人开始计数,数到$m的人出列
function josephu($n, $k, $m) {
$ret = array();
$rl = new RoundList($n);
for ($i = 0; $i < $k; $i += 1) {
if ($i == 0) {
$p = $rl->head;
} else {
$p = $p->next;
}
}
for ($i = 0; $i < $n; $i += 1) {
for ($j = 1; $j < $m; $j += 1) {
$p = $p->next;
}
$ret[] = $p->no;
$p = $rl->delete($p);
}
//return $ret;
print '<pre>';
print_r($ret);
print '</pre>';
}
josephu(20, 5, 7);