Home  >  Article  >  php教程  >  PHP中使用数组实现堆栈数据结构的代码

PHP中使用数组实现堆栈数据结构的代码

WBOY
WBOYOriginal
2016-06-13 12:02:18979browse

在堆栈中,最后压入的数据(进栈),将会被最先弹出(出栈)。
即在数据存储时采用“先进后出”的数据结构。
PHP中,将数组当做一个栈,主要是使用array_push()和array_pop()两个系统函数来完成。
入栈主要是利用array_push()函数向第一个参数的数组尾部添加一个或多个元素,然后返回新数组的长度,示例如下:

复制代码 代码如下:


$zhan=array("WEB");//声明一个数组当做栈
array_push($zhan,"PHP");//将字符串压入栈(数组)中
array_push($zhan,"WWW.CHHUA.COM");//再压入一个元素
print_r($zhan);//打印数组内容
?>


出栈主要是利用array_pop()函数将数组的最后一个函数弹出,并将数组的长度减1,示例如下:

复制代码 代码如下:


$zhan=array("WEB","www.chhua.com","WEB开发笔记","PHP","网站建设");//声明一个数组当做栈
array_pop($zhan);//将字符串出栈(数组)中
print_r($zhan);//打印数组内容 Array([0] => WEB[1] => www.chhua.com[2] => WEB开发笔记[3] => PHP)
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn