A Stack is a very important data structure in computer science, It works on the principle of last-in-first-out (LIFO ). The element which inserted last is the first element to be popped. In this tutorial, You will learn about stack data structure and how to implement a stack in PHP.
Previous posts about stack data structure
Stack implementation in C using an array
Stack implementation using Linked list
In Stack, insert and delete operations are done from a single end. Insertion and deletion operations are called as push and pop.
Push – To insert an element in a Stack.
Pop – To delete an element from a Stack.
Before any push operation in a Stack, we need to check whether there is a sufficient space available for a new element. If memory is not available then we throw an exception of Stack Overflow. Similarly in pop operation, if a stack is empty then we throw an exception of Stack Underflow.
Implementation of Stack in PHP
We have learned about a stack and it’s basic operations. Let’s implement them in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<?php class Stack { protected $stack; protected $size; public function __construct($size = 50) { //Initialize stack $this->stack = array(); //Initialize stack size $this->size = $size; } /** * Insert an element in a stack * @param type $data */ public function push($data) { //Check stack overflow if(count($this->stack) < $this->size) { //Inserts an element at the beginning array_unshift($this->stack, $data); } else { // If stack is full then throw stack overflow exception throw new RuntimeException("Stack overflow"); } } /** * Removes an element from a stack * */ public function pop() { // If stack is empty if (empty($this->stack)) { throw new RuntimeException("Stack underflow"); } else { return array_shift($this->stack); } } } $stack = new Stack(); $stack->push(4); $stack->push(5); echo $stack->pop(); // Pop 5 $stack->push(7); $stack->push(9); $stack->push(8); echo $stack->pop(); // Pop 8 echo $stack->pop(); // Pop 9 |
Application of Stack Data Structure
i) When functions are called.
ii) In recursion.
iii) Evaluation and conversion of expressions.