【PHP 实现数据结构】栈

以前介绍过 “队列” 是一种特殊的线性表,这里再介绍另一种特殊的线性表 “栈”php

什么是栈segmentfault

栈是一种后入先出的数据结构,它只能容许在列表的一端进行操做。容许操做的一端称为栈顶。数据结构

栈有两个基本操做,元素压入栈和元素弹出栈,操做示例图。this

image.png

代码实现spa

咱们来实现上述两个基本操做,和实际应用中经常使用的其余几个操做。code

  • push 入栈
  • pop 出栈
  • peek 栈顶元素预览
  • length 栈存储的元素个数
  • clear 清空栈
<?php

/**
 * Class Stack
 */
class Stack
{
    protected $top = 0;

    protected $dataStore = [];

    /**
     * 入栈
     * @param $data
     */
    public function push($data)
    {
        $this->dataStore[$this->top++] = $data;
    }

    /**
     * 出栈
     * @return mixed
     */
    public function pop()
    {
        return $this->dataStore[--$this->top];
    }

    /**
     * 预览,查看栈顶元素,可是不弹出
     * @return mixed
     */
    public function peek()
    {
        return $this->dataStore[$this->top - 1];
    }

    /**
     * 栈长度
     * @return int
     */
    public function length() {
        return $this->top;
    }

    /**
     * 清空栈元素
     */
    public function clear() {
        $this->top = 0;
        $this->dataStore = [];
    }
}

示例blog

$stack = new Stack();
$stack->push(1);
$stack->push(2);
$stack->push(3);
echo "stack length:",$stack->length(),PHP_EOL;
$stack->pop();
$stack->pop();
$stack->push(4);
echo "stack top:",$stack->peek(),PHP_EOL;
$stack->clear();
echo "stack length:",$stack->length(),PHP_EOL;

image.png

相关文章
相关标签/搜索