偶遇奇葩php面試題->(使用php模擬js中的 push pop getMin)

使用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();
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章