华大大的博客

PHP 实现简单顺序栈

使用PHP的数组函数实现简单的顺序栈。

class SimpleStack
{
    private $_stack = [];
    private $_size;

    public function __construct($size = 10)
    {
        $this->_size = $size;
    }

    public function pop()
    {
        if (count($this->_stack) == 0) {
            return false;
        }
        return array_pop($this->_stack);
    }

    public function push($value)
    {
        if (count($this->_stack) == $this->_size) {
            return false; //满栈
        }
        array_push($this->_stack, $value);
        return true;
    }

    public function isEmpty()
    {
        return current($this->_stack) == false;
    }

    public function size()
    {
        return count($this->_stack);
    }
}

$stack = new SimpleStack(12);
var_dump($stack->isEmpty());  # true
$stack->push('First');
$stack->push('Second');
var_dump($stack->pop());  # Second
var_dump($stack->pop());  # First
var_dump($stack->size());  # 1

⬆️

写的不错,赞助一下主机费

扫一扫,用支付宝赞赏
扫一扫,用微信赞赏
RabbitMQ PHP使用 2019-01-23

暂无评论~~