这篇文章主要介绍了关于PHP数据结构基础之栈,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
栈和队列
栈和队列和之前讲到的实战PHP数据结构基础之双链表 一样都是线性结构。
栈有什么特点
栈遵循后进先出的原则(LIFO)。这意味着栈只有一个出口用来压入元素和弹出元素,当我们执行压入或者弹出操作的时候要注意栈是否已满或者栈是否是空的。
常见操作
还是废话不多说,直接来看我们对栈执行的常用操作。
push
pop
top
isEmpty
...
PHP实现
首先我们定义一个StackInterface。
interface StackInterface { public function push(string $item); public function pop(); public function top(); public function isEmpty(); }
来看基于数组的栈实现
class ArrStack implements StackInterface { private $stack; private $limit; public function __construct(int $limit = 20) { $this->limit = $limit; $this->stack = []; } public function __get($val) { return $this->$val; } public function push(string $data = null) { if (count($this->stack) < $this->limit) { array_push($this->stack, $data); } else { throw new \OverflowException('stack is overflow'); } } public function pop() { if ($this->isEmpty()) { throw new \UnderflowException('stack is empty'); } else { return array_pop($this->stack); } } public function isEmpty() { return empty($this->stack); } public function top() { return end($this->stack); }
得益于PHP强大的array结构,我们轻而易举的写出来了栈的基本操作方法。果然世界上最好的语言名不虚传。
那有同学说了,你说栈和之前的链表都是线性结构,那可不可以直接使用链表实现栈呢?这个问题非常犀利啊,答案是可以的。
可能机智的同学已经猜到了,我之前已经定义了一个栈接口,那栈的实现肯定不止只有上面一种哈。来看基于链表的实现。
class LinkedListStack implements StackInterface { private $stack; private $limit; public function __construct(int $limit) { $this->limit = $limit; $this->stack = new LinkedList(); } public function top() { return $this->stack->getNthNode($this->stack->getSize() - 1)->data; } public function isEmpty() { return $this->stack->getSize() === 0; } public function pop() { if ($this->isEmpty()) { throw new \UnderflowException('stack is empty'); } else { $lastItem = $this->top(); $this->stack->deleteLast(); return $lastItem; } } public function push(string $item) { if ($this->stack->getSize() < $this->limit) { $this->stack->insert($item); } else { throw new \OverflowException('stack is overflow'); } }
里面涉及到了之前的链表实现,不了解细节的同学可以去这里看看。有同学又问,那栈到底有什么用处?这个问题非常好,来看一个需求。
请实现一个数学表达式检查类,输入一个下面表达式,预期结果为true。
"8 * (9 -2) + { (4 * 5) / ( 2 * 2) }
下面的为false。
"5 * 8 * 9 / ( 3 * 2 ) )"
下面的也为false。
"[{ (2 * 7) + ( 15 - 3) ]"
自己想一下,再往下看实现。
class ExpressionChecker { //$expressions[] = "8 * (9 -2) + { (4 * 5) / ( 2 * 2) }"; //$expressions[] = "5 * 8 * 9 / ( 3 * 2 ) )"; //$expressions[] = "[{ (2 * 7) + ( 15 - 3) ]"; public function check(string $expression): bool { $stack = new \SplStack(); foreach (str_split($expression) as $item) { switch ($item) { case '{': case '[': case '(': $stack->push($item); break; case '}': case ']': case ')': if ($stack->isEmpty()) return false; $last = $stack->pop(); if ( $item == '{' && $last != '}' || $item == '(' && $last != ')' || $item == '[' && $last != ']' ) return false; break; } } if ($stack->isEmpty()) { return true; } return false; } }
专题系列
PHP基础数据结构专题系列目录地址:https://github.com/... 主要使用PHP语法总结基础的数据结构和算法。还有我们日常PHP开发中容易忽略的基础知识和现代PHP开发中关于规范、部署、优化的一些实战性建议,同时还有对Javascript语言特点的深入研究。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
以上是PHP数据结构基础之栈的详细内容。更多信息请关注PHP中文网其他相关文章!

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

你应该关心DependencyInjection(DI),因为它能让你的代码更清晰、更易维护。1)DI通过解耦类,使其更模块化,2)提高了测试的便捷性和代码的灵活性,3)使用DI容器可以管理复杂的依赖关系,但要注意性能影响和循环依赖问题,4)最佳实践是依赖于抽象接口,实现松散耦合。

是的,优化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)优化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,并避免使用

theKeyStrategiestosiminificallyBoostphpapplicationPermenCeare:1)useOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)优化AtabaseInteractionswithPreparedStateTemtStatementStatementSandProperIndexing,3)配置

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3汉化版
中文版,非常好用

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)