In this tutorial, you learn about the stack data structure and its implementation in Python, Java, and C/C++.
In this article, you will learn-
What is Stack Data Structure?
The stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows adding and eliminating elements in a specific request. Each time an element is added, it goes on the top of the stack and the only element that can be removed is the element that is at the top of the stack, much the same as a pile of objects.
A stack is a valuable data structure in programming. It is much the same as a heap of plates kept on top of each other.
Consider the things you can do with such a heap of plates
- Put a new plate on top
- Remove the top plate
On the off chance that you need the plate at the bottom, you should initially eliminate all the plates on top. Such a course of action is called Last In First Out – the last item that is the primary item to go out.
LIFO Principle of Stack
In programming terms, putting an item on top of the stack is called a push, and eliminating an item is called pop.
In the above picture, albeit item 2 was kept last, it was eliminated first – so it follows the Last In First Out(LIFO) standard.
We can execute a stack in any programming language like C, C++, Java, Python, or C#, yet the determination is essentially the equivalent.
Basic Operations of Stack
A stack is an object (an abstract data type – ADT) that allows the accompanying tasks:
- Push: Add an element to the top of a stack
- Pop: Remove an element from the top of a stack
- IsEmpty: Check if the stack is vacant
- IsFull: Check if the stack is full
- Peek: Get the value of the top element without eliminating it
Working of Stack Data Structure
The operation works in as follows:
- A pointer called TOP is used to monitor the top element in the stack.
- While instating the stack, we set its value to – 1 so we can check if the stack is vacant by comparing TOP == – 1.
- On pushing an element, we increase the value of TOP and spot the new element in the position highlighted by TOP.
- On popping an element, we return the element highlighted by TOP and reduce its value.
- before pushing, we check if the stack is already full
- before popping, we check if the stack is already vacant
Stack Implementations in Python, Java, C, and C++
The most common stack implementation is using arrays, but it can also be implemented using lists.
Python
# Stack implementation in python # Creating a stack def create_stack(): stack = [] return stack # Creating an empty stack def check_empty(stack): return len(stack) == 0 # Adding items into the stack def push(stack, item): stack.append(item) print("pushed item: " + item) # Removing an element from the stack def pop(stack): if (check_empty(stack)): return "stack is empty" return stack.pop() stack = create_stack() push(stack, str(1)) push(stack, str(2)) push(stack, str(3)) push(stack, str(4)) print("popped item: " + pop(stack)) print("stack after popping an element: " + str(stack))
Java
// Stack implementation in Java class Stack { private int arr[]; private int top; private int capacity; // Creating a stack Stack(int size) { arr = new int[size]; capacity = size; top = -1; } // Add elements into stack public void push(int x) { if (isFull()) { System.out.println("OverFlow\nProgram Terminated\n"); System.exit(1); } System.out.println("Inserting " + x); arr[++top] = x; } // Remove element from stack public int pop() { if (isEmpty()) { System.out.println("STACK EMPTY"); System.exit(1); } return arr[top--]; } // Utility function to return the size of the stack public int size() { return top + 1; } // Check if the stack is empty public Boolean isEmpty() { return top == -1; } // Check if the stack is full public Boolean isFull() { return top == capacity - 1; } public void printStack() { for (int i = 0; i <= top; i++) { System.out.println(arr[i]); } } public static void main(String[] args) { Stack stack = new Stack(5); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.pop(); System.out.println("\nAfter popping out"); stack.printStack(); } }
C
// Stack implementation in C #include <stdio.h> #include <stdlib.h> #define MAX 10 int count = 0; // Creating a stack struct stack { int items[MAX]; int top; }; typedef struct stack st; void createEmptyStack(st *s) { s->top = -1; } // Check if the stack is full int isfull(st *s) { if (s->top == MAX - 1) return 1; else return 0; } // Check if the stack is empty int isempty(st *s) { if (s->top == -1) return 1; else return 0; } // Add elements into stack void push(st *s, int newitem) { if (isfull(s)) { printf("STACK FULL"); } else { s->top++; s->items[s->top] = newitem; } count++; } // Remove element from stack void pop(st *s) { if (isempty(s)) { printf("\n STACK EMPTY \n"); } else { printf("Item popped= %d", s->items[s->top]); s->top--; } count--; printf("\n"); } // Print elements of stack void printStack(st *s) { printf("Stack: "); for (int i = 0; i < count; i++) { printf("%d ", s->items[i]); } printf("\n"); } // Driver code int main() { int ch; st *s = (st *)malloc(sizeof(st)); createEmptyStack(s); push(s, 1); push(s, 2); push(s, 3); push(s, 4); printStack(s); pop(s); printf("\nAfter popping out\n"); printStack(s); }
C++
// Stack implementation in C++ #include <stdlib.h> #include <iostream> using namespace std; #define MAX 10 int size = 0; // Creating a stack struct stack { int items[MAX]; int top; }; typedef struct stack st; void createEmptyStack(st *s) { s->top = -1; } // Check if the stack is full int isfull(st *s) { if (s->top == MAX - 1) return 1; else return 0; } // Check if the stack is empty int isempty(st *s) { if (s->top == -1) return 1; else return 0; } // Add elements into stack void push(st *s, int newitem) { if (isfull(s)) { printf("STACK FULL"); } else { s->top++; s->items[s->top] = newitem; } size++; } // Remove element from stack void pop(st *s) { if (isempty(s)) { printf("\n STACK EMPTY \n"); } else { printf("Item popped= %d", s->items[s->top]); s->top--; } size--; cout << endl; } // Print elements of stack void printStack(st *s) { printf("Stack: "); for (int i = 0; i < size; i++) { cout << s->items[i] << " "; } cout << endl; } // Driver code int main() { int ch; st *s = (st *)malloc(sizeof(st)); createEmptyStack(s); push(s, 1); push(s, 2); push(s, 3); push(s, 4); printStack(s); pop(s); cout << "\nAfter popping out\n"; printStack(s); }
Stack Time Complexity
For the array-based implementation of a stack, the push and pop operations take constant time, i.e. O(1).
Applications of Stack Data Structure
Although stack is a simple data structure to actualize, it is extremely amazing. The most common uses of a stack are:
- To reverse a word – Put all the letters in a stack and pop them out. In view of the LIFO request of the stack, you will get the letters backward request.
- In compilers – Compilers use the stack to calculate the value of expressions like 2 + 4/5 * (7 – 9) by changing the expression to prefix or postfix structure.
- In browsers – The back catch in a browsers saves all the URLs you have visited previously in a stack. Each time you visit another page, it is added on top of the stack. At the point when you press the back catch, the current URL is removed from the stack, and the previous URL is accessed.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.