使用php模拟js中的 push pop getMin
/*
模拟js中的 push pop getMin
不能用数组函数
不能用字符串函数
不能用for , foreach
不能使用splice shift
不能使用count length
*/
class Obj
{
protected $data;
protected $min;
public function __construct($data = [])
{
if (!$data) {
$this->data = [];
}
reset($this->data);
}
public function push($abc)
{
$this->data[] = $abc;
return $this->data;
}
public function pop()
{
end($this->data);
$key = key($this->data);
unset($this->data[$key]);
return $this->data;
}
public function getMin()
{
end($this->data);
$end_key = key($this->data);
reset($this->data);
if (empty($this->min)) {
$this->min = $this->data[0];
}
next($this->data);
$value = current($this->data);
$key = key($this->data);
if ($end_key == 0) {
return $this->min;
}
if ($this->min <= $value) {
if ($key != $end_key) {
unset($this->data[$key]);
return $this->getMin();
} else {
return $this->min;
}
} else {
$this->min = $value;
return $this->getMin();
}
}
}