the SplStack is simply a SplDoublyLinkedList with an iteration mode IT_MODE_LIFO and IT_MODE_KEEP
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
La classe SplStack fournit l'interface de base pour implémenter une pile,
basée sur une liste doublement chaînée en définissant le mode de l'itérateur à
SplDoublyLinkedList::IT_MODE_LIFO
.
Exemple #1 Exemple de SplStack
<?php
$q = new SplStack();
$q[] = 1;
$q[] = 2;
$q[] = 3;
foreach ($q as $elem) {
echo $elem."\n";
}
?>
L'exemple ci-dessus va afficher :
3 2 1
the SplStack is simply a SplDoublyLinkedList with an iteration mode IT_MODE_LIFO and IT_MODE_KEEP
<?php
//SplStack Mode is LIFO (Last In First Out)
$q = new SplStack();
$q[] = 1;
$q[] = 2;
$q[] = 3;
$q->push(4);
$q->add(4,5);
$q->rewind();
while($q->valid()){
echo $q->current(),"\n";
$q->next();
}
?>
Output
5
4
3
2
1
<?php
// Exercise: Implement Queue using Stacks
class MyQueue {
protected $queue;
/**
* Initialize your data structure here.
*/
function __construct() {
$this->queue = new \SplStack;
}
/**
* Push element x to the back of queue.
* @param Integer $x
* @return NULL
*/
function push($x) {
$this->queue->push($x);
}
/**
* Removes the element from in front of queue and returns that element.
* @return Integer
*/
function pop() {
$length = count($this->queue);
$temp = [];
while(!$this->queue->isEmpty()){
$rv = $this->queue->pop();
if(!$this->queue->isEmpty()){
$temp[] = $rv;
}
}
for($i = count($temp)-1; $i >= 0; $i--){
$this->queue->push($temp[$i]);
}
return $rv;
}
/**
* Get the front element.
* @return Integer
*/
function peek() {
return $this->queue->bottom();
}
/**
* Returns whether the queue is empty.
* @return Boolean
*/
function empty() {
return $this->queue->isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* $obj = MyQueue();
* $obj->push($x);
* $ret_2 = $obj->pop();
* $ret_3 = $obj->peek();
* $ret_4 = $obj->empty();
*/