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:
- One cannot push more elements into a full stack.
- One cannot pop any more elements from an empty stack.
Declaring a stack was done in the last sections as well. Let's keep that in mind as we proceed.
Operation 1: Push
-
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.
-
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 variabletop
by 1 and insert the element at the indextop
of the stack.
- 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 itstop
, which was 3. We then increment it to 4. Now, we insert the elementx
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.
-
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.
-
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 thetop
variable by 1, and return the temporary variable that stored the popped element.
- 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.