一个简单的栈,利用array_push array_pop来实现

 * 定义一个接口类
 * Interface Stack
 */
interface Stack
{
    public function push($data);
    public function pop();
    public function peek();
    public function getSize();
    public function isEmpty();
}

class ArrayStack implements Stack
{
    private $data=[];
    public function __construct()
    {

    }

    public function getSize()
    {
        return count($this->data);
    }

    public function isEmpty()
    {
        return empty($this->data);
    }

    public function push($node)
    {
        return array_push($this->data, $node);
    }

    public function pop()
    {
        return array_pop($this->data);
    }

    public function peek()
    {
        $last_key = array_key_last($this->data);
        return $this->data[$last_key];
    }
    public function __toString()
    {
        // TODO: Implement __toString() method.
        $str = "";
        $str .= "Stack: ";
        $str .= "[";
        foreach ($this->data as $value) {
            $str .= $value.", ";
        }
        $str = trim($str, ', ');
        $str .= ']';
        return $str;
    }

}
$stack = new ArrayStack();
$stack->push("asfasf");
$stack->push('zhang');
echo $stack;


你可能感兴趣的:(栈)