【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

相關文章
相關標籤/搜索