Basic Operations in Stack Data Structure with Implementations
Last Updated :
03 Nov, 2024
In order to make manipulations in a stack, there are certain operations provided to us for Stack, which include:
- push() to insert an element into the stack
- pop() to remove an element from the stack
- top() Returns the top element of the stack.
- isEmpty() returns true if the stack is empty else false.
- size() returns the size of the stack.
In this post, we will see how to perform these operations on Stack.

Push Operation in Stack:
Push operation adds an item to the stack.
If the stack is full, then it is said to be an Overflow condition.
Below is a sample program to show Push operation in Stack.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
stack<int> s; // creating a stack of integers
s.push(1); // This pushes 1 to the stack top
s.push(2); // This pushes 2 to the stack top
s.push(3); // This pushes 3 to the stack top
s.push(4); // This pushes 4 to the stack top
s.push(5); // This pushes 5 to the stack top
// printing the stack
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
// The above loop prints "5 4 3 2 1"
}
Java
import java.util.ArrayDeque;
public class StackExample {
public static void main(String[] args) {
ArrayDeque<Integer> s = new ArrayDeque<>();
s.push(1); // Pushing 1 to the top
s.push(2); // Pushing 2 to the top
s.push(3); // Pushing 3 to the top
s.push(4); // Pushing 4 to the top
s.push(5); // Pushing 5 to the top
// Printing in reverse order
while (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
// The output will be "5 4 3 2 1"
}
}
Python
# Python Code:
stack = []
stack.append(1) # This pushes 1 to the stack top
stack.append(2) # This pushes 2 to the stack top
stack.append(3) # This pushes 3 to the stack top
stack.append(4) # This pushes 4 to the stack top
stack.append(5) # This pushes 5 to the stack top
# printing the stack
while stack:
print(stack[-1], end=" ")
stack.pop()
# The above loop prints "5 4 3 2 1"
# This code is contributed by Sakshi
C#
using System;
using System.Collections.Generic;
class Program {
static void Main()
{
Stack<int> s = new Stack<int>(); // Creating a stack
// of integers
s.Push(1); // Pushing 1 to the stack top
s.Push(2); // Pushing 2 to the stack top
s.Push(3); // Pushing 3 to the stack top
s.Push(4); // Pushing 4 to the stack top
s.Push(5); // Pushing 5 to the stack top
// Printing the stack
while (s.Count > 0) {
Console.Write(
s.Peek()
+ " "); // Peek() gets the top element
// without removing it
s.Pop(); // Pop() removes the top element
}
// The above loop prints "5 4 3 2 1"
}
}
JavaScript
class Stack {
constructor() {
this.stack = [];
}
push(value) {
this.stack.push(value); // Pushes the value to the stack top
}
top() {
return this.stack[this.stack.length - 1]; // Returns the element at the top of the stack
}
pop() {
return this.stack.pop(); // Removes and returns the top element of the stack
}
isEmpty() {
return this.stack.length === 0; // Checks if the stack is empty
}
}
function main() {
const s = new Stack(); // Creating a stack
s.push(1); // Pushing 1 to the stack top
s.push(2); // Pushing 2 to the stack top
s.push(3); // Pushing 3 to the stack top
s.push(4); // Pushing 4 to the stack top
s.push(5); // Pushing 5 to the stack top
// Printing the stack
while (!s.isEmpty()) {
console.log(s.top() + " "); // Outputting the top element
s.pop(); // Removing the top element
}
// The above loop prints "5 4 3 2 1"
}
main(); // Calling the main function
Pop Operation in Stack:
Pop operation is used to remove an item from the stack.
The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Below is a sample program to show Pop operation in Stack.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
stack<int> s; // creating a stack of integers
s.push(1); // This pushes 1 to the stack top
s.push(2); // This pushes 2 to the stack top
s.push(3); // This pushes 3 to the stack top
s.push(4); // This pushes 4 to the stack top
s.push(5); // This pushes 5 to the stack top
// Now, let us remove elements from the stack using pop function
while (!s.empty()) {
cout << s.top() << " ";
s.pop(); // removes the top element from the stack
}
}
Java
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque<Integer> s = new ArrayDeque<>(); /
s.push(1); // Pushing 1 to the stack top
s.push(2);
s.push(3);
s.push(4);
s.push(5);
// Removing elements from the stack using pop function
while (!s.isEmpty()) {
System.out.print(s.peek() + " "); /
s.pop();
}
}
}
Python
stack = []
stack.append(1) # This pushes 1 to the stack top
stack.append(2) # This pushes 2 to the stack top
stack.append(3) # This pushes 3 to the stack top
stack.append(4) # This pushes 4 to the stack top
stack.append(5) # This pushes 5 to the stack top
# Now, let us remove elements from the stack using pop function
while stack:
print(stack[-1], end=" ")
stack.pop() # removes the top element from the stack
C#
using System;
using System.Collections.Generic;
class Program {
static void Main()
{
// Creating a stack of integers
Stack<int> s = new Stack<int>();
// Pushing elements onto the stack
s.Push(1); // This pushes 1 to the stack top
s.Push(2); // This pushes 2 to the stack top
s.Push(3); // This pushes 3 to the stack top
s.Push(4); // This pushes 4 to the stack top
s.Push(5); // This pushes 5 to the stack top
// Removing elements from the stack using Pop function
while (s.Count > 0) {
Console.Write(s.Peek() + " "); // Displaying the top element without removing it
s.Pop(); // Removes the top element from the stack
}
}
}
JavaScript
// Creating a stack
let stack = [];
// Pushing elements to the stack
stack.push(1); // This pushes 1 to the stack top
stack.push(2); // This pushes 2 to the stack top
stack.push(3); // This pushes 3 to the stack top
stack.push(4); // This pushes 4 to the stack top
stack.push(5); // This pushes 5 to the stack top
// Removing elements from the stack using pop function
while (stack.length > 0) {
console.log(stack[stack.length - 1]); // Print the top element
stack.pop(); // Removes the top element from the stack
}
Top Operation in Stack:
Top operation is used to return the top element of the stack.
Below is a sample program to show Pop operation in Stack.
C++
#include <bits/stdc++.h>
using namespace std;
int topElement(stack<int>& s) { return s.top(); }
int main()
{
stack<int> s; // creating a stack of integers
s.push(1); // This pushes 1 to the stack top
cout << topElement(s)
<< endl; // Prints 1 since 1 is present at the
// stack top
s.push(2); // This pushes 2 to the stack top
cout << topElement(s)
<< endl; // Prints 2 since 2 is present at the
// stack top
s.push(3); // This pushes 3 to the stack top
cout << topElement(s)
<< endl; // Prints 3 since 3 is present at the
// stack top
}
Java
import java.util.ArrayDeque;
public class StackExample {
public static void main(String[] args) {
ArrayDeque<Integer> s = new ArrayDeque<>();
// Pushing 1 to the stack top
s.push(1);
System.out.println(s.peek()); // Prints 1
// Pushing 2 to the stack top
s.push(2);
System.out.println(s.peek()); // Prints 2
// Pushing 3 to the stack top
s.push(3);
System.out.println(s.peek()); // Prints 3
}
}
Python
# Python code:
def topElement(s):
return s[-1]
s = [] # creating a stack of integers
s.append(1) # This pushes 1 to the stack top
print(topElement(s)) # Prints 1 since 1 is present at the stack top
s.append(2) # This pushes 2 to the stack top
print(topElement(s)) # Prints 2 since 2 is present at the stack top
s.append(3) # This pushes 3 to the stack top
print(topElement(s)) # Prints 3 since 3 is present at the stack top
# This code is contributed by Sakshi
C#
using System;
using System.Collections.Generic;
class Program
{
static int TopElement(Stack<int> s)
{
return s.Peek();
}
static void Main()
{
Stack<int> s = new Stack<int>(); // creating a stack of integers
s.Push(1); // This pushes 1 to the stack top
Console.WriteLine(TopElement(s)); // Prints 1 since 1 is present at the stack top
s.Push(2); // This pushes 2 to the stack top
Console.WriteLine(TopElement(s)); // Prints 2 since 2 is present at the stack top
s.Push(3); // This pushes 3 to the stack top
Console.WriteLine(TopElement(s)); // Prints 3 since 3 is present at the stack top
}
}
JavaScript
function topElement(s) {
return s[s.length - 1];
}
// Main function
function main() {
let s = []; // Creating an array to act as a stack
s.push(1); // Pushing 1 to the stack
console.log(topElement(s)); // Prints 1 since 1 is at the top of the stack
s.push(2); // Pushing 2 to the stack
console.log(topElement(s)); // Prints 2 since 2 is at the top of the stack
s.push(3); // Pushing 3 to the stack
console.log(topElement(s)); // Prints 3 since 3 is at the top of the stack
}
// Calling the main function
main();
//THis code is contributed by Utkarsh
isEmpty Operation in Stack:
isEmpty operation is a boolean operation that is used to determine if the stack is empty or not.
This operation will return true if the stack is empty, else false.
Below is a sample program to show Pop operation in Stack.
C++
#include <bits/stdc++.h>
using namespace std;
bool isEmpty(stack<int>& s)
{
bool isStackEmpty
= s.empty(); // checking whether stack is empty or
// not and storing it into isStackEmpty
// variable
return isStackEmpty; // returning bool value stored in
// isStackEmpty
}
int main()
{
stack<int> s;
// The if - else conditional statements below prints
// "Stack is empty."
if (isEmpty(s)) {
cout << "Stack is empty." << endl;
}
else {
cout << "Stack is not empty." << endl;
}
s.push(1); // Inserting value 1 to the stack top
// The if - else conditional statements below prints
// "Stack is not empty."
if (isEmpty(s)) {
cout << "Stack is empty." << endl;
}
else {
cout << "Stack is not empty." << endl;
}
}
Java
import java.util.Stack;
public class Main {
public static boolean isEmpty(Stack<Integer> s) {
return s.empty();
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
if (isEmpty(s)) {
System.out.println("Stack is empty.");
} else {
System.out.println("Stack is not empty.");
}
s.push(1);
if (isEmpty(s)) {
System.out.println("Stack is empty.");
} else {
System.out.println("Stack is not empty.");
}
}
}
Python
# Python Code:
def isEmpty(s):
isStackEmpty = len(s) == 0 # checking whether stack is empty or
# not and storing it into isStackEmpty variable
return isStackEmpty # returning bool value stored in isStackEmpty
s = []
# The if - else conditional statements below prints "Stack is empty."
if isEmpty(s):
print("Stack is empty.")
else:
print("Stack is not empty.")
s.append(1) # Inserting value 1 to the stack top
# The if - else conditional statements below prints "Stack is not empty."
if isEmpty(s):
print("Stack is empty.")
else:
print("Stack is not empty.")
# This code is contributed by Sakshi
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to check if a stack is empty
static bool IsEmpty(Stack<int> s)
{
return s.Count == 0;
}
static void Main()
{
Stack<int> s = new Stack<int>();
// Check if the stack is empty
if (IsEmpty(s))
{
Console.WriteLine("Stack is empty.");
}
else
{
Console.WriteLine("Stack is not empty.");
}
// Push a value (1) onto the stack
s.Push(1);
// Check if the stack is empty after pushing a value
if (IsEmpty(s))
{
Console.WriteLine("Stack is empty.");
}
else
{
Console.WriteLine("Stack is not empty.");
}
}
}
JavaScript
function isEmpty(stack) {
// checking whether stack is empty or not
return stack.length === 0;
}
function main() {
const s = [];
// The if - else conditional statements below prints "Stack is empty."
if (isEmpty(s)) {
console.log("Stack is empty.");
} else {
console.log("Stack is not empty.");
}
s.push(1); // Inserting value 1 to the stack top
// The if - else conditional statements below prints "Stack is not empty."
if (isEmpty(s)) {
console.log("Stack is empty.");
} else {
console.log("Stack is not empty.");
}
}
// Run the main function
main();
//This code is contributed by Monu.
OutputStack is empty.
Stack is not empty.
size() Operation in Stack:
Size operation in Stack is used to return the count of elements that are present inside the stack.
Below is a sample program to show Pop operation in Stack.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
stack<int> s; // creating a stack of integers
cout << s.size()
<< endl; // Prints 0 since the stack is empty
s.push(1); // This pushes 1 to the stack top
s.push(2); // This pushes 2 to the stack top
cout << s.size() << endl; // Prints 2 since the stack
// contains two elements
s.push(3); // This pushes 3 to the stack top
cout << s.size() << endl; // Prints 3 since the stack
// contains three elements
}
Java
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque<Integer> s = new ArrayDeque<>();
System.out.println(s.size()); // Prints 0 since the stack is empty
s.push(1); // Pushing 1 to the stack top
s.push(2); // Pushing 2 to the stack top
System.out.println(s.size()); // Prints 2 since the stack contains two elements
s.push(3); // Pushing 3 to the stack top
System.out.println(s.size()); // Prints 3 since the stack contains three elements
}
}
Python
# PYthon Code:
stack = [] # creating an empty list as a stack
print(len(stack)) # Prints 0 since the stack is empty
stack.append(1) # This appends 1 to the stack
stack.append(2) # This appends 2 to the stack
print(len(stack)) # Prints 2 since the stack contains two elements
stack.append(3) # This appends 3 to the stack
print(len(stack)) # Prints 3 since the stack contains three element
# This code is contributed by Sakshi
C#
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
Stack<int> s = new Stack<int>(); // creating a stack of integers
Console.WriteLine(s.Count); // Prints 0 since the stack is empty
s.Push(1); // This pushes 1 to the stack top
s.Push(2); // This pushes 2 to the stack top
Console.WriteLine(s.Count); // Prints 2 since the stack contains two elements
s.Push(3); // This pushes 3 to the stack top
Console.WriteLine(s.Count); // Prints 3 since the stack contains three elements
}
}
//This code is contribiuted by Kishan.
JavaScript
let stack = []; // Creating an array to simulate a stack
console.log(stack.length); // Prints 0 since the stack is empty
stack.push(1); // This pushes 1 to the stack top
stack.push(2); // This pushes 2 to the stack top
console.log(stack.length); // Prints 2 since the stack contains two elements
stack.push(3); // This pushes 3 to the stack top
console.log(stack.length); // Prints 3 since the stack contains three elements
//This code is contributed by Aman.
Applications of Stack
Stack Data Structure
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem