A stack is a type of abstract data type. In a stack, data is stored in a sequential list format, and the primary operations, such as adding or deleting an element, occur at one end (top) of the stack. This is why it is referred to as Last In First Out (LIFO).

The concept of a stack is quite simple and its meaning is directly conveyed in its translation. The word “stack” means a “pile”, indicating that the data will be stored in a stacked manner. Consider if you were at a restaurant. You are asked to take a plate, typically you would take one from the top of the stack where the plates are arranged. Similarly, if a worker cleans and stacks the plates, they would also place them on top. This concept in computer science is similar to the practical application seen in everyday life.

The basic operations of the stack are –

create(max_stack_size)

Create a new stack.

isFull(stack, max_stack_size)

Checking if the stack is full. Many may question whether it is necessary to verify that the stack is full? need Because the stack must be stored in the computer’s memory, and since memory is not infinite, verification is needed.

push(stack, item)

To insert or add a value to the stack.

isEmpty(stack)

To check if a variable is on the stack.

pop(stack,item)

To delete a value from the stack.

Push and pop using C++:

#include <iostream>
#define MAX_STACK_SIZE 50
 
using namespace std;
 
int ourstack[MAX_STACK_SIZE],top=0;
 
// This function is to push in stack
int pushinstack(int item) 
{
    if(top>MAX_STACK_SIZE-1)
    {
        cout<<"\nStack is full";
    }
    else
    {
        ourstack[top]=item;
        top++;
    }
}
 
// This function is to display all values in stack
int displaystack() 
{
    if(top>0)
    {
        cout<<"\nValues in stack: ";
        for(int i=0;i<top;i++)
        {
            cout<<ourstack[i]<<" ";
        }
    }
    else
    cout<<"\nThere is no value in stack";
}
 
// This function is to pop from stack
void popfromstack() 
{
    if(top<0)
    {
        cout<<"\nStack is Empty";
    }
    else
    {
        cout<<"\npopped : "<<ourstack[top-1];
        top--;
    }
}
 
int main()
{
     
    displaystack();
     
    pushinstack(5);
    pushinstack(10);
    pushinstack(15);
    pushinstack(20);
     
    displaystack();
     
    popfromstack();
     
    displaystack();
     
    return 0;
}
0 0 votes
Article Rating
0
Would love your thoughts, please comment.x
()
x