THE SIMPLICITY OF STACK


Stack, the most frequently used data structure. Stack, as the name suggests, keeps on stacking up the data one above the other. Consider an example of stacking up books in a box. The implementation of stack in your program is similar to that.

Stack is often referred to as Last In First Out (LIFO). Why?Β  Consider the same example of the books in box. You insert book by book in the box and would be able to remove the last placed book first and the first book you placed would be taken out last.

Stacks can be implemented using Arrays or Linked List. In this article, we shall see how it is implemented by using Arrays.

Β What are the operations to be performed to achieve this task? Visualize the books in the box. If the box is empty, you start loading it up with books. If it is full, you stop it and close the cover. And the inverse, you would unload unless there are no books left or until the book you are searching for is found.Β  Use the same operations here, but let’s change the naming for simplicity. Push(), Pop(), PrintStack(). As the names suggest, Push() performs insertion of element into the stack, Pop() performs deletion of elements from the stack and PrintStack() just prints the stack.

What do you do before adding the books? Make sure, the box has enough space. We use a similar analogy with the Push() operation. If the stack is full, Stop inserting the elements and let the user know that the stack is full. Let us also consider a variable top and initialize with -1 so that we can keep track of the topmost item.

<pre class="wp-block-syntaxhighlighter-code">
void pushStack()
{
if(top<MAX-1){
    int value;
    printf("Enter the element: ");
    scanf("%d",&value);
    ++top;
    stack[top]=value;
    printf("Pushed....\n");
}
else{
    printf("!!!!!!!! ERROR: Stack is overflown... !!!!!!!!\n");
}
}
</pre>

Here, top and the stack array are declared as global variables. Just check if the top is less than the MAX storage allocated in the array, as long as it is less, you are good to Push the values into the stack.Β  If the top value exceeds, Throw an error message to the user. As you see, we are incrementing the top just before adding an element such that we are able to insert the values in the desired position i.e during the first push, we get
top=0, stack[0] Β Β Β —– First Push
top=1, stack[1]Β Β Β  —– Second Push
top=2, stack[2]Β Β Β  —– Second Push … you see the pattern.

Time to remove the books from the box. Before doing that, just check if the box is empty, if it is, where would the book appear? Let’s go for the implementation using popStack() operation.

<pre class="wp-block-syntaxhighlighter-code [code language="css"]">
void popStack()
{
    if(top==-1)
        printf("Stack is empty, cannot pop\n");
    else{
        stack[top]=0;
        top--;
        printf("Popped...\n");
    }
}
</pre>

As seen, we are just checking if the stack is empty, we are doing that by top==-1 . Since you need to pop the element that is currently being pointed by top, pop the element and then decrement the top value. Here I am just initializing the removed value by 0 and decrementing the top.

Now, I want to see how many books are present in the box. For this, we are using the printStack() with a simple printf and printing the elements until the top. If there are no elements in the stack for printing, just print a simple error message.

<pre class="wp-block-syntaxhighlighter-code">
void printStack(){
    if(top==-1)
    printf("\n~~~~~~~~~~~No elements to print~~~~~~~~~~~\n");

    else{
        for (int i = top; i >= 0; i--)    
        printf("%d ",stack[i]);
    }

}
</pre>
Illustration of Stack

Using these three simple functions, a stack operation using arrays can be performed. Now let’s merge the code.

<pre class="wp-block-syntaxhighlighter-code">
#include<stdio.h>
#include<stdlib.h>
#define MAX 5
int stack[MAX];
int count =0;
int top = -1;

void pushStack()
{
    
    if(top<MAX-1){
        int value;
        printf("Enter the element: ");
        scanf("%d",&value);
        ++top;
        stack[top]=value;
        printf("Pushed....\n");
    }
    else{
        printf("!!!!!!!! ERROR: Stack is overflown... !!!!!!!!\n");
    }
}

void popStack()
{
    if(top==-1)
        printf("Stack is empty, cannot pop\n");
    else{
        stack[top]=0;
        top--;
        printf("Popped...\n");
    }
}

void  printStack(){
    if(top==-1)
    printf("\n~~~~~~~~~~~No elements to print~~~~~~~~~~~\n");

    else{
        for (int i = top; i >=0  ; i--)    
        printf("%d ",stack[i]);
    }

}

void main()
{

do{
    printf("Select and option\n1)Push element\t2)Pop Element\t3)Print Stack\n");
    int choice;
    scanf("%d",&choice);
    switch (choice)
    {
    case 1:
            pushStack();
            break;
    case 2:
            popStack();
            break;
    case 3:
            printStack();
            break;
    default:
        printf("Invalid Option\n");
        break;

    }

}while(1);
}
</pre>

From real-time undo, redo to actual stacking of function calls in the memory, the use of stack can be seen everywhere.

Feel free to modify and experiment. Thanks for reading. Happy learning.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.