A stack is a useful data structure in programming. It is just like a pile of plates kept on top of each other.
Think about the things you can do with such a pile of plates
If you want the plate at the bottom, you have to first remove all the plates on top. Such kind of arrangement is called Last In First Out - the last item that was placed is the first item to go out.
In programming terms, putting an item on top of the stack is called "push" and removing an item is called "pop".
In the above image, although item 2 was kept last, it was removed first - so it follows the Last In First Out(LIFO) principle.
We can implement stack in any programming language like C, C++, Java, Python or C#, but the specification is pretty much the same.
A stack is an object or more specifically an abstract data structure(ADT) that allows the following operations:
Push
: Add element to top of stackPop
: Remove element from top of stackIsEmpty
: Check if stack is emptyIsFull
: Check if stack is fullPeek
: Get the value of the top element without removing itThe operations work as follows:
TOP == -1
.The most common stack implementation is using arrays, but it can also be implemented using lists.
Here is an implementation using arrays and C programming language.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
struct stack
{
int items[MAX];
int top;
};
typedef struct stack st;
void createEmptyStack(st *s)
{
s->top=-1;
}
int isfull(st *s)
{
if (s->top==MAX-1)
return 1;
else
return 0;
}
int isempty(st *s)
{
if (s->top==-1)
return 1;
else
return 0;
}
void push(st *s)
{
int newitem;
printf("Enter item to be inserted: ");
scanf("%d",&newitem);
if (isfull(s))
{
printf("STACK FULL");
}
else
{
s->top++;
s->items[s->top]=newitem;
}
}
void pop (st *s)
{
if (isempty(s))
{
printf("\n STACK EMPTY \n");
}
else
{
printf("Item popped= %d",s->items[s->top]);
s->top--;
}
}
void main()
{
int ch;
int loop;
loop=1;
st *s;
createEmptyStack(s);
do
{
printf("\n ***STACK OPERATIONS");
printf("\n 1. PUSH");
printf("\n 2. POP");
printf("\n 3. EXIT");
printf("\n ***************");
printf("\n Enter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
push(s);
break;
case 2:
pop(s);
break;
case 3:
printf("THANK YOU");
loop=0;
exit(0);
default:
printf("Invalid choice");
}
} while(loop);
getch();
}
Although stack is a simple data structure to implement, it is very powerful. The most common uses of a stack are:
It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:
Disabling AdBlock on Programiz. We do not use intrusive ads.
or
Donate on Paypal