【PHP 实现数据结构】栈

栏目: IT技术 · 发布时间: 4年前

内容简介:之前介绍过 “队列” 是一种特殊的线性表,这里再介绍另外一种特殊的线性表 “栈”栈是一种后入先出的数据结构,它只能允许在列表的一端进行操作。允许操作的一端称为栈顶。栈有两个基本操作,元素压入栈和元素弹出栈,操作示例图。

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

什么是栈

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

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

【PHP 实现数据结构】栈

代码实现

我们来实现上述两个基本操作,和实际应用中常用的其他几个操作。

  • 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 = [];
    }
}

示例

$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;

【PHP 实现数据结构】栈


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

D3.js in Action

D3.js in Action

Elijah Meeks / Manning Publications / 2014-3 / USD 44.99

Table of Contents Part 1: An Introduction to D3 1 An introduction to D3.js 2 Information Visualization Data Flow 3 D ata-Driven Design and Interaction Part 2: The Pillars of Information......一起来看看 《D3.js in Action》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具