Home > Article > Backend Development > Introduction to the data structure stack (SplStack) of the PHP SPL standard library, splsplstack_PHP tutorial
The stack (Stack) is a special linear table, because it can only be at one end of the linear table Insert or delete elements (i.e. push and pop)
SplStack is to inherit the double linked list (SplDoublyLinkedList) to implement the stack.
The class summary is as follows:
Easy to use as follows:
//把栈想象成一个颠倒的数组 $stack = new SplStack(); /** * 可见栈和双链表的区别就是IteratorMode改变了而已,栈的IteratorMode只能为: * (1)SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP (默认值,迭代后数据保存) * (2)SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_DELETE (迭代后数据删除) */ $stack->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_DELETE); $stack->push('a'); $stack->push('b'); $stack->push('c'); $stack->pop(); //出栈 $stack->offsetSet(0, 'first');//index 为0的是最后一个元素 foreach($stack as $item) { echo $item . PHP_EOL; // first a } print_R($stack); //测试IteratorMode