Operations in Stack

Operations in Stack Implemented Using an Array.

Push, Pop, and Other Operations in Stack Implemented Using an Array

We have already covered the basics of a stack and its implementation using arrays. Now, we can learn about the operations one can perform on a stack while executing them using arrays.

We concluded our last section with two important points:

  1. One cannot push more elements into a full stack.
  2. One cannot pop any more elements from an empty stack.
example

Declaring a stack was done in the last sections as well. Let's keep that in mind as we proceed.

Operation 1: Push

  1. The first step is to define a stack. If we have already created the stack and declared its fundamental parts, pushing an element requires checking if there is any space left in the stack.

  2. Call the isFull function, which we discussed in the previous sections. If the stack is full, then we cannot push any more elements; this situation is known as stack overflow. Otherwise, increase the variable top by 1 and insert the element at the index top of the stack.

example
  1. This is how we push an element into a stack array. Suppose we have an element x to insert into a stack array of size 4. We first check if the stack is full and find that it is not. We retrieve its top, which was 3. We then increment it to 4. Now, we insert the element x at index 4, and we are done.

Operation 2: Pop

Popping an element is very similar to inserting an element. You should try this yourself as well, as there are very subtle changes.

  1. Again, define a stack and cover all the fundamental parts. You should be familiar with this by now. Popping an element requires checking if there is any element left in the stack to pop.

  2. Call the isEmpty function, which we practiced in the previous sections. If the stack is empty, we cannot pop any element since there are none left; this situation is known as stack underflow. Otherwise, store the topmost element in a temporary variable, decrease the top variable by 1, and return the temporary variable that stored the popped element.

example
  1. So, this is how we pop an element from a stack array. Suppose we make a pop call in a stack array of size 4. first checked if it was empty, and found it was not empty. retrieved its top which was 4 here. Stored the element at 4. made it 3 by decreasing it once. Now, just return the element x, and popping is done.

So, this was known about the concepts behind pushing and popping elements in a stack.