Stack
Stack
Stack
Stack Concept
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 rst remove all the plates on top. Such
kind of arrangement is called Last In First Out - the last item that was placed is the rst
item to go out.
https://www.programiz.com/dsa/stack 1/6
8/27/2018 Stack
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 rst - 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 speci cation is pretty much the same.
https://www.programiz.com/dsa/stack 2/6
8/27/2018 Stack
1. A pointer called TOP is used to keep track of the top element in the stack.
2. When initializing the stack, we set its value to -1 so that we can check if the stack is
empty by comparing TOP == -1 .
3. On pushing an element, we increase the value of TOP and place the new element in
the position pointed to by TOP .
4. On popping an element, we return the element pointed to by TOP and reduce its
value.
5. Before pushing, we check if stack is already full
6. Before popping, we check if stack is already empty
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
struct stack
{
int items[MAX];
int top;
};
typedef struct stack st;
https://www.programiz.com/dsa/stack 3/6
8/27/2018 Stack
Use of stack
Although stack is a simple data structure to implement, it is very powerful. The most
common uses of a stack are:
To reverse a word - Put all the letters in a stack and pop them out. Because of LIFO
order of stack, you will get the letters in reverse order.
In compilers - Compilers use stack to calculate the value of expressions like 2+4/5*(7-
9) by converting the expression to pre x or post x form.
In browsers - The back button in a browser saves all the urls you have visited
previously in a stack. Each time you visit a new page, it is added on top of the stack.
When you press the back button, the current URL is removed from the stack and the
previous url is accessed.
Stack
Queue
Circular Queue
Linked List
DFS algorithm
Adjacency List
Adjacency Matrix
Kruskal's Algorithm
Prim's Algorithm
Dynamic Programming
Dijkstra's Algorithm
https://www.programiz.com/dsa/stack 5/6
8/27/2018 Stack
Subscribe
ABOUT
CONTACT
ADVERTISE
https://www.programiz.com/dsa/stack 6/6