Understanding stack

The stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. This means that there is only one end for the stack, which is used to add items and remove items from the structure. The addition of new items in the stack is known as push, and push whilst removing an item is known as pop. Since we only have one end to operate, we are always going to push an item at that end, and when we pop, the last item from that end will be popped up. The top most elements in the stack that are also at the very beginning of the stack end are known as the top. If we consider the following image, we can see that after each pop and push operation, the top changes. Also, we are performing the operation at the top of the stack, not at the beginning or middle of the stack. We have to be careful about popping an element when the stack is empty, as well as pushing an element when the stack is full. We might have a stack overflow if we want to push more elements than its capacity.

From our earlier discussion, we now know that we have four basic operations in a stack:

  • Push: add an item at the top of the stack.
  • Pop: remove the top item of the stack.
  • Top: returns the top item of the stack. It is not the same as pop, as it does not remove the item, it just gets the value for us.
  • isEmpty: checks whether the stack is empty or not.

Now let us implement the stack using PHP, but in different ways. First, we will try to implement the stack using PHP's built-in array function. Then we will look at how to build a stack without using PHP's built-in functions, but by using some other data structures, such as linked lists.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset