思路:
1 兩個棧 data、min
2 往data中入數時同時往min中入數
3 當新入元素小於、等於棧頂元素時,元素既入data又入min;當新入元素大於棧頂時新元素入data不入min
4 彈棧時當data棧頂與min棧頂相同時都彈;當data棧頂大於min棧頂時只彈data
代碼
<?php
class Stack{
private $data;
private $min;
public function __construct()
{
$this->data = new SplStack();
$this->min = new SplStack();
}
public function push($e)
{
if ($this->data->isEmpty() && $this->min->isEmpty()) {
$this->data->push($e);
$this->min->push($e);
}
if ($e <= $this->min->top()) {
$this->data->push($e);
$this->min->push($e);
}
if ($e > $this->min->top()) {
$this->data->push($e);
}
}
public function pop()
{
if ($this->data->isEmpty() || $this->min->isEmpty()) {
exit(-1);
}
if ($this->data->top() > $this->min->top()) {
return $this->data->pop();
} else {
$this->data->pop();
return $this->min->pop();
}
}
public function getMin()
{
return $this->min->pop();
}
}