Home >Backend Development >PHP Problem >How to achieve the effect of stack and queue?

How to achieve the effect of stack and queue?

autoload
autoloadOriginal
2021-03-10 17:13:471553browse

Stack and Queue

  1. Stack and Queue both belong to the data structure

  2. StackisLIFO

  3. ##QueueisFIFO

1. Implement stack array

array_push(array input array, value should be pushed into the first value at the end of array )

array_pop(): Pop the last element from the stack.

<?php
$array=array();
array_push($array,"1");
array_push($array,14,34,89,67);
array_pop($array);//将67出栈
print_r($array);//Array ( [0] => 1 [1] => 14 [2] => 34 [3] => 89 )
?>

2. Implement the array of

queue

array_shift(): Dequeue and remove the first element in the queue

array_unshift(): Insert an element at the beginning of the array

<?php
$array=array();

array_push($array,1,14,34,89,67);
print_r($array);//Array ( [0] => 1 [1] => 14 [2] => 34 [3] => 89 [4] => 67 )
echo "<br>";

array_shift($array);//将先进入队列的数组元素,出队列
print_r($array);//Array ( [0] => 14 [1] => 34 [2] => 89 [3] => 67 )
echo "<br>";

array_unshift($array,&#39;66&#39;);//在队列头部插入一个元素
print_r($array);//Array ( [0] => 66 [1] => 14 [2] => 34 [3] => 89 [4] => 67 )
?>

Recommended:

php tutorial,php video tutorial

The above is the detailed content of How to achieve the effect of stack and queue?. For more information, please follow other related articles on the PHP Chinese website!

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