内容简介:之前介绍过 “队列” 是一种特殊的线性表,这里再介绍另外一种特殊的线性表 “栈”栈是一种后入先出的数据结构,它只能允许在列表的一端进行操作。允许操作的一端称为栈顶。栈有两个基本操作,元素压入栈和元素弹出栈,操作示例图。
之前介绍过 “队列” 是一种特殊的线性表,这里再介绍另外一种特殊的线性表 “栈”
什么是栈
栈是一种后入先出的数据结构,它只能允许在列表的一端进行操作。允许操作的一端称为栈顶。
栈有两个基本操作,元素压入栈和元素弹出栈,操作示例图。
代码实现
我们来实现上述两个基本操作,和实际应用中常用的其他几个操作。
- 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;
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 数据结构 – 用于构建文件系统的数据结构?
- 荐 用Python解决数据结构与算法问题(三):线性数据结构之栈
- 数据结构和算法面试题系列-C指针、数组和结构体
- 请问二叉树等数据结构的物理存储结构是怎样的?
- 数据结构——单链表
- 常用数据结构
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Single Page Web Applications
Michael Mikowski、Josh Powell / Manning Publications / 2013-9-30 / USD 44.99
Code for most web sites mostly runs on the server. When a user clicks on a link, the site reacts slowly because the browser sends information to the server and the server sends it back again before di......一起来看看 《Single Page Web Applications》 这本书的介绍吧!