Time and Space Complexity analysis of Stack operations
Last Updated :
23 Jul, 2025
What is Stack?
Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order. A stack can be implemented using Arrays or Linked Lists.
Complexity analysis of different stack operations:
1) push():
This operation pushes an element on top of the stack and the top pointer points to the newly pushed element. It takes one parameter and pushes it onto the stack.
Below is the implementation of push() using Array :
C++
#include <bits/stdc++.h>
using namespace std;
class Stack {
public:
int stack[10];
int MAX = 10;
int top;
Stack() { top = -1; }
void push(int val)
{
// If top is pointing to
// maximum size of stack
if (top >= MAX - 1) {
// Stack is full
cout << "Stack Overflow\n";
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
cout << val
<< " pushed into stack successfully !\n";
}
};
int main()
{
Stack st;
st.push(1);
st.push(2);
return 0;
}
Java
// Java code to push element on top of stack
import java.io.*;
class GFG {
static class Stack {
int stack[] = new int[10];
int MAX = 10;
int top;
void stack() { top = -1; }
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
System.out.println("Stack Overflow");
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
System.out.println(
val + " pushed into stack successfully !");
}
}
public static void main(String[] args)
{
Stack st = new Stack();
st.push(1);
st.push(2);
}
}
// This code is contributed by lokeshmvs21.
Python
# Python code to push elements in stack
class Stack:
def __init__(self):
self.stack = [0] * 10
self.MAX = 10
self.top = -1
def push(self, val):
# If top is pointing to maximum size of stack
if self.top >= self.MAX - 1:
# Stack is full
print("Stack Overflow")
return
# Point top to new top
self.top += 1
# Insert new element at top of stack
self.stack[self.top] = val
print(str(val) + " pushed into stack successfully !\n")
if __name__ == "__main__":
st = Stack()
st.push(1)
st.push(2)
# This code is contributed by adityamaharshi21
C#
// Include namespace system
using System;
public class GFG
{
class Stack
{
public int[] stack = new int[10];
public int MAX = 10;
public int top;
public void _stack()
{
this.top = -1;
}
public void push(int val)
{
// If top is pointing to maximum size of stack
if (this.top >= this.MAX - 1)
{
// Stack is full
Console.WriteLine("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
Console.WriteLine(val.ToString() + " pushed into stack successfully !");
}
}
public static void Main(String[] args)
{
var st = new Stack();
st.push(1);
st.push(2);
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// JS code for above operation
class Stack {
constructor() {
this.stack = [];
this.MAX = 10;
this.top = -1;
}
push(val) {
// If top is pointing to
// maximum size of stack
if (this.top >= this.MAX - 1) {
// Stack is full
console.log("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
console.log(val, " pushed into stack successfully !");
}
};
let st = new Stack();
st.push(1);
st.push(2);
// This code is contributed by adityamaharshi21
Output1 pushed into stack successfully !
2 pushed into stack successfully !
Complexity Analysis:
- Time Complexity: O(1), In the push function a single element is inserted at the last position. This takes a single memory allocation operation which is done in constant time.
- Auxiliary Space: O(1), As no extra space is being used.
Below is the implementation of push() using Linked List :
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val)
{
data = val;
next = NULL;
}
};
class Stack {
public:
Node* top;
Stack() { top = NULL; }
void push(int val)
{
// Create new node temp and
// allocate memory in heap
Node* temp = new Node(val);
// If stack is empty
if (!top) {
top = temp;
cout << val
<< " pushed into stack successfully !\n";
return;
}
temp->next = top;
top = temp;
cout << val
<< " pushed into stack successfully !\n";
}
};
int main()
{
Stack st;
st.push(1);
st.push(2);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static class Node{
int data;
Node next;
Node(int val){
this.data = val;
this.next = null;
}
}
static class Stack{
Node top;
Stack(){
top = null;
}
void push(int val){
// Create new node temp and allocate memory in heap
Node temp = new Node(val);
// If stack is empty
if(top!=null){
top = temp;
System.out.println(val + " pushed into stack successfully !");
return;
}
temp.next = top;
top = temp;
System.out.println(val + " pushed into stack successfully !");
}
}
public static void main (String[] args) {
Stack st = new Stack();
st.push(1);
st.push(2);
}
}
Python
# Python program to insert an element in a stack using linked list
class Node:
def __init__(self, val):
self.data = val
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, val):
temp = Node(val)
if not self.top:
self.top = temp
print(val, "pushed into stack successfully!")
return
temp.next = self.top
self.top = temp
print(val, "pushed into stack successfully!")
st = Stack()
st.push(1)
st.push(2)
# This code is contributed by adityamaharshi21
C#
// C# implementation of push() using Linked List
using System;
public class GFG {
class Node {
public int data;
public Node next;
public Node(int val)
{
this.data = val;
this.next = null;
}
}
class Stack {
Node top;
public Stack() { top = null; }
public void push(int val)
{
// Create new node temp and allocate memory in
// heap
Node temp = new Node(val);
// If stack is empty
if (top != null) {
top = temp;
Console.WriteLine(
val
+ " pushed into stack successfully !");
return;
}
temp.next = top;
top = temp;
Console.WriteLine(
val + " pushed into stack successfully !");
}
}
static public void Main()
{
// Code
Stack st = new Stack();
st.push(1);
st.push(2);
}
}
// This code is contributed by lokeshmvs21.
JavaScript
// JS code for push operation using linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class Stack {
constructor() {
this.top=null;
}
push(val) {
// Create new node temp and
// allocate memory in heap
let temp = new Node(val);
// If stack is empty
if (this.top==null) {
this.top = temp;
console.log(val, " pushed into stack successfully !");
return;
}
temp.next = this.top;
this.top = temp;
console.log(val, " pushed into stack successfully !");
}
};
let st = new Stack();
st.push(1);
st.push(2);
// This code is contributed by adityamaharshi21
Output1 pushed into stack successfully !
2 pushed into stack successfully !
Complexity Analysis:
- Time Complexity: O(1), Only a new node is created and the pointer of the last node is updated. This includes only memory allocation operations. Hence it can be said that insertion is done in constant time.
- Auxiliary Space: O(1), No extra space is used.
2) pop():
This operation removes the topmost element in the stack and returns an error if the stack is already empty.
Below is the implementation of pop() using Array:
C++
#include <bits/stdc++.h>
using namespace std;
class Stack {
public:
int stack[10];
int MAX = 10;
int top;
Stack() { top = -1; }
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
cout << "Stack Overflow\n";
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
cout << val
<< " pushed into stack successfully !\n";
}
void pop()
{
// Stack is already empty
if (top < 0) {
cout << "Stack Underflow";
}
else {
// Removing top of stack
int x = stack[top--];
cout << "Element popped from stack : " << x
<< "\n";
}
}
};
int main()
{
Stack st;
st.push(1);
st.pop();
st.pop();
return 0;
}
Java
import java.io.*;
class GFG {
static class Stack {
int[] stack = new int[10];
int MAX = 10;
int top;
Stack() { top = -1; }
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
System.out.println("Stack Overflow");
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
System.out.println(
val + " pushed into stack successfully !");
}
void pop()
{
// Stack is already empty
if (top < 0) {
System.out.print("Stack Underflow");
}
else {
// Removing top of stack
int x = stack[top--];
System.out.println(
"Element popped from stack : " + x);
}
}
}
public static void main(String[] args)
{
Stack st = new Stack();
st.push(1);
st.pop();
st.pop();
}
}
// This code is contributed by lokeshmvs21.
Python
# Python program for above approach
class Stack:
def __init__(self):
self.stack = [None]*10
self.MAX = 10
self.top = -1
def push(self, val):
# If top is pointing to maximum size of stack
if self.top >= self.MAX-1:
# Stack is full
print('Stack Overflow')
return
# Point top to new top
self.top += 1
# Insert new element at top of stack
self.stack[self.top] = val
print(val, 'pushed into stack successfully !')
# Stack is already empty
def pop(self):
if self.top < 0:
print('Stack Underflow')
else:
# Removing top of stack
x = self.stack[self.top]
self.top -= 1
print('Element popped from stack:', x)
st = Stack()
st.push(1)
st.pop()
st.pop()
# This code is contributed by adityamaharshi21
C#
using System;
public class GFG {
class Stack {
public int[] stack = new int[10];
public int MAX = 10;
public int top;
public void _stack() { this.top = -1; }
public void push(int val)
{
// If top is pointing to maximum size of stack
if (this.top >= this.MAX - 1) {
// Stack is full
Console.WriteLine("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
Console.WriteLine(
val.ToString()
+ " pushed into stack successfully !");
}
public void pop()
{
// Stack is already empty
if (this.top <= 0) {
Console.WriteLine("Stack Underflow");
}
else {
// Removing top of stack
int x = this.stack[this.top--];
Console.WriteLine(
"Element popped from stack : "
+ x.ToString());
}
}
}
public static void Main(String[] args)
{
var st = new Stack();
st.push(1);
st.pop();
st.pop();
}
}
JavaScript
// JS code for pop operation using array
class Stack {
constructor() {
this.stack = [];
this.MAX = 10;
this.top = -1;
}
push(val) {
// If top is pointing to
// maximum size of stack
if (this.top >= this.MAX - 1) {
// Stack is full
console.log("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
console.log(val, " pushed into stack successfully !");
}
pop() {
// Stack is already empty
if (this.top < 0) {
console.log("Stack Underflow");
}
else {
// Removing top of stack
let x = this.stack[this.top--];
console.log("Element popped from stack : ", x);
}
}
};
// Driver code
let st = new Stack();
st.push(1);
st.pop();
st.pop();
// This code is contributed by adityamaharshi21
Output1 pushed into stack successfully !
Element popped from stack : 1
Stack Underflow
Complexity Analysis:
- Time Complexity: O(1), In array implementation, only an arithmetic operation is performed i.e., the top pointer is decremented by 1. This is a constant time function.
- Auxiliary Space: O(1), No extra space is utilized for deleting an element from the stack.
Below is the implementation of pop() using Linked List :
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val)
{
data = val;
next = NULL;
}
};
class Stack {
public:
Node* top;
Stack() { top = NULL; }
void push(int val)
{
// Create new node temp and allocate memory in heap
Node* temp = new Node(val);
// If stack is empty
if (!top) {
top = temp;
cout << val
<< " pushed into stack successfully !\n";
return;
}
temp->next = top;
top = temp;
cout << val
<< " pushed into stack successfully !\n";
}
void pop()
{
Node* temp;
// Check for stack underflow
if (top == NULL) {
cout << "Stack Underflow\n"
<< endl;
return;
}
else {
// Assign top to temp
temp = top;
cout << "Element popped from stack : "
<< temp->data << "\n";
// Assign second node to top
top = top->next;
// This will automatically destroy
// the link between first node and second node
// Release memory of top node
// i.e delete the node
free(temp);
}
}
};
int main()
{
Stack st;
st.push(1);
st.pop();
st.pop();
return 0;
}
Java
import java.io.*;
class GFG {
static class Node {
int data;
Node next;
Node(int val)
{
this.data = val;
this.next = null;
}
}
static class Stack {
Node top;
Stack() { top = null; }
void push(int val)
{
// Create new node temp and allocate memory in
// heap
Node temp = new Node(val);
// If stack is empty
if (top != null) {
top = temp;
System.out.println( val+" pushed into stack successfully !");
return;
}
temp.next = top;
top = temp;
System.out.println(
val + " pushed into stack successfully !");
}
void pop()
{
// Check for stack underflow
Node temp;
if (top == null) {
System.out.println("Stack Underflow");
}
else {
// Assign top to temp
temp = top;
System.out.println("Element popped from stack : " + temp.data);
// Assign second node to top
top = top.next;
// This will automatically destroy
// the link between first node and second
// node
}
}
}
public static void main(String[] args)
{
Stack st = new Stack();
st.push(1);
st.pop();
st.pop();
}
}
Python
class Node:
def __init__(self, val):
self.data = val
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, val):
# Create new node temp and allocate memory in heap
temp = Node(val)
# If stack is empty
if not self.top:
self.top = temp
print(val, "pushed into stack successfully !")
return
temp.next = self.top
self.top = temp
print(val, "pushed into stack successfully !")
def pop(self):
# Check for stack underflow
if self.top is None:
print("Stack Underflow")
return
# Assign top to temp
temp = self.top
print("Element popped from stack :", {temp.data})
# Assign second node to top
self.top = self.top.next
# This will automatically destroy
# the link between first node and second node
# Release memory of top node
# i.e delete the node
del temp
st = Stack()
st.push(1)
st.pop()
st.pop()
# This code is contributed by aadityamaharshi21.
C#
using System;
class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Stack {
public Node top;
public Stack() { top = null; }
public void push(int val)
{
// Create new node temp and allocate memory in heap
Node temp = new Node(val);
// If stack is empty
if (top == null) {
top = temp;
Console.WriteLine(
val + " pushed into stack successfully !");
return;
}
temp.next = top;
top = temp;
Console.WriteLine(
val + " pushed into stack successfully !");
}
public void pop()
{
Node temp;
// Check for stack underflow
if (top == null) {
Console.WriteLine("Stack Underflow\n"
+ "\n");
return;
}
else {
// Assign top to temp
temp = top;
Console.WriteLine("Element popped from stack : "
+ temp.data + "\n");
// Assign second node to top
top = top.next;
// This will automatically destroy
// the link between first node and second node
// Release memory of top node
// i.e delete the node
temp = null;
}
}
}
class Program {
static void Main(string[] args)
{
Stack st = new Stack();
st.push(1);
st.pop();
st.pop();
}
}
// This code is contributed by adityamaharshi21.
JavaScript
// JavaScript program for above approach
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
}
push(val) {
// Create new node temp and allocate memory in heap
let temp = new Node(val);
// If stack is empty
if (!this.top) {
this.top = temp;
console.log(val + " pushed into stack successfully !");
return;
}
temp.next = this.top;
this.top = temp;
console.log(val + " pushed into stack successfully !");
}
pop() {
let temp;
// Check for stack underflow
if (this.top == null) {
console.log("Stack Underflow");
return;
} else {
// Assign top to temp
temp = this.top;
console.log("Element popped from stack : " + temp.data);
// Assign second node to top
this.top = this.top.next;
// This will automatically destroy
// the link between first node and second node
// Release memory of top node
// i.e delete the node
temp = null;
}
}
}
let st = new Stack();
st.push(1);
st.pop();
st.pop();
// This code is contributed by adityamaharshi21
Output1 pushed into stack successfully !
Element popped from stack : 1
Stack Underflow
Complexity Analysis:
- Time Complexity: O(1), Only the first node is deleted and the top pointer is updated. This is a constant time operation.
- Auxiliary Space: O(1). No extra space is utilized for deleting an element from the stack.
3) peek():
This operation prints the topmost element of the stack.
Below is the Implementation of peek() using Array:
C++
#include <bits/stdc++.h>
using namespace std;
class Stack {
public:
int stack[10];
int MAX = 10;
int top;
Stack() { top = -1; }
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
cout << "Stack Overflow\n";
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
cout << val
<< " pushed into stack successfully !\n";
}
int peek()
{
// Stack is already empty then
// we can't get peek element
if (top < 0) {
cout << "Stack is Empty\n";
return 0;
}
else {
// Retrieving top element from stack
int x = stack[top];
return x;
}
}
};
int main()
{
Stack st;
st.push(1);
st.push(2);
cout << "Peek element of stack : "
<< st.peek() << "\n";
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static class Stack {
int[] stack = new int[10];
int MAX = 10;
int top;
Stack() { top = -1; }
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
System.out.println("Stack Overflow");
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
System.out.println(
val + " pushed into stack successfully !");
}
int peek()
{
// Stack is already empty then
// we can't get peek element
if (top < 0) {
System.out.println("Stack is Empty\n");
return 0;
}
else {
// Retrieving top element from stack
int x = stack[top];
return x;
}
}
}
public static void main (String[] args) {
Stack st = new Stack();
st.push(1);
st.push(2);
System.out.println("Peek element of stack : "
+ st.peek() + "\n");
}
}
// This code is contributed by akashish__
Python
class Stack:
def __init__(self):
self.stack = [0] * 10
self.MAX = 10
self.top = -1
def push(self, val):
# If top is pointing to maximum size of stack
if self.top >= self.MAX - 1:
# Stack is full
print("Stack Overflow")
return
# Point top to new top
self.top += 1
# Insert new element at top of stack
self.stack[self.top] = val
print(val, " pushed into stack successfully !")
def peek(self):
# Stack is already empty then
# we can't get peek element
if self.top < 0:
print("Stack is Empty")
return 0
else:
# Retrieving top element from stack
x = self.stack[self.top]
return x
def main():
st = Stack()
st.push(1)
st.push(2)
print("Peek element of stack : ", st.peek())
return 0
if __name__ == "__main__":
main()
# This code is contributed by adityamaharshi21.
C#
// C# program for peek operation in Stack
using System;
public class GFG {
class Stack {
public int[] stack = new int[10];
public int MAX = 10;
public int top;
public void _stack() { this.top = -1; }
public void push(int val)
{
// If top is pointing to maximum size of stack
if (this.top >= this.MAX - 1) {
// Stack is full
Console.WriteLine("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
Console.WriteLine(
val.ToString()
+ " pushed into stack successfully !\n");
}
public int peek()
{
// Stack is already empty then
// we can't get peek element
if (this.top < 0) {
Console.WriteLine("Stack is Empty");
return 0;
}
else {
// Retrieving top element from stack
int x = stack[this.top];
return x;
}
}
}
public static void Main(String[] args)
{
var st = new Stack();
st.push(1);
st.push(2);
Console.WriteLine("Peek element of stack : "
+ st.peek());
}
}
// This code is contributed by adityamaharshi21.
JavaScript
// JS code for above approach
class Stack {
constructor() {
this.stack = [];
this.MAX = 10;
this.top = -1;
}
Stack() { top = -1; }
push(val) {
// If top is pointing to
// maximum size of stack
if (this.top >= this.MAX - 1) {
// Stack is full
console.log("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
console.log(val, " pushed into stack successfully !");
}
peek() {
// Stack is already empty then
// we can't get peek element
if (this.top < 0) {
console.log("Stack is Empty");
return 0;
}
else {
// Retrieving top element from stack
let x = this.stack[this.top];
return x;
}
}
};
let st = new Stack;
st.push(1);
st.push(2);
console.log("Peek element of stack : ", st.peek())
return 0;
// This code is contributed by adityamaharshi21
Output1 pushed into stack successfully !
2 pushed into stack successfully !
Peek element of stack : 2
Complexity Analysis:
- Time Complexity: O(1), Only a memory address is accessed. This is a constant time operation.
- Auxiliary Space: O(1), No extra space is utilized to access the value.
Below is the implementation of peek() using Linked List :
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val)
{
data = val;
next = NULL;
}
};
class Stack {
public:
Node* top;
Stack() { top = NULL; }
void push(int val)
{
// Create new node temp and
// allocate memory in heap
Node* temp = new Node(val);
// If stack is empty
if (!top) {
top = temp;
cout << val
<< " pushed into stack successfully !\n";
return;
}
temp->next = top;
top = temp;
cout << val
<< " pushed into stack successfully !\n";
}
bool isEmpty()
{
// If top is NULL it means that
// there are no elements are in stack
return top == NULL;
}
int peek()
{
// If stack is not empty,
// return the top element
if (!isEmpty())
return top->data;
else
cout << "Stack is Empty\n";
exit(1);
}
};
int main()
{
Stack st;
st.push(1);
cout << "Peek element of stack : "
<< st.peek() << "\n";
return 0;
}
Java
import java.util.Scanner;
class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Stack {
public Node top;
public Stack() { top = null; }
public void push(int val)
{
// Create new node temp and
// allocate memory in heap
Node temp = new Node(val);
// If stack is empty
if (top == null) {
top = temp;
System.out.println(
val + " pushed into stack successfully!");
return;
}
temp.next = top;
top = temp;
System.out.println(
val + " pushed into stack successfully!");
}
public boolean isEmpty()
{
// If top is null it means that
// there are no elements are in stack
return top == null;
}
public int peek()
{
// If stack is not empty,
// return the top element
if (!isEmpty()) {
return top.data;
}
else {
System.out.println("Stack is Empty");
System.exit(1);
}
return 0;
}
}
public class Main {
public static void main(String[] args)
{
Stack st = new Stack();
st.push(1);
System.out.println("Peek element of stack: "
+ st.peek());
}
}
Python
class Node:
def __init__(self, val):
self.data = val
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, val):
temp = Node(val)
if self.top is None:
self.top = temp
print(val,"pushed into stack successfully !")
return
temp.next = self.top
self.top = temp
print(val," pushed into stack successfully !")
def is_empty(self):
return self.top is None
def peek(self):
if not self.is_empty():
return self.top.data
else:
print("Stack is Empty")
exit(1)
st = Stack()
st.push(1)
print("Peek element of stack:",st.peek())
C#
using System;
class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Stack {
public Node top;
public Stack() { top = null; }
public void push(int val)
{
// Create new node temp and
// allocate memory in heap
Node temp = new Node(val);
// If stack is empty
if (top == null) {
top = temp;
Console.WriteLine(val + " pushed into stack successfully !");
return;
}
temp.next = top;
top = temp;
Console.WriteLine(val + " pushed into stack successfully !");
}
public bool isEmpty()
{
// If top is NULL it means that
// there are no elements are in stack
return top == null;
}
public int peek()
{
// If stack is not empty,
// return the top element
if (!isEmpty())
return top.data;
else
Console.WriteLine("Stack is Empty");
Environment.Exit(1);
return -1; // this line will never be reached
}
}
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.push(1);
Console.WriteLine("Peek element of stack: " + st.peek() + "\n");
}
}
JavaScript
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
}
push(val) {
let temp = new Node(val);
if (this.top === null) {
this.top = temp;
console.log(val + " pushed into stack successfully !");
return;
}
temp.next = this.top;
this.top = temp;
console.log(val + " pushed into stack successfully !");
}
isEmpty() {
return this.top === null;
}
peek() {
if (!this.isEmpty()) {
return this.top.data;
}
else {
console.log("Stack is Empty");
process.exit(1);
}
}
}
const st = new Stack();
st.push(1);
console.log("Peek element of stack:", st.peek());
Output1 pushed into stack successfully !
Peek element of stack : 1
Complexity Analysis:
- Time Complexity: O(1). In linked list implementation also a single memory address is accessed. It takes constant time.
- Auxiliary Space: O(1). No extra space is utilized to access the element because only the value in the node at the top pointer is read.
4) isempty():
This operation tells us whether the stack is empty or not.
Below is the implementation of isempty() using Array :
C++
#include <bits/stdc++.h>
using namespace std;
class Stack {
public:
int stack[10];
int MAX = 10;
int top;
Stack() { top = -1; }
void push(int val)
{
// If top is pointing to
// maximum size of stack
if (top >= MAX - 1) {
// Stack is full
cout << "Stack Overflow\n";
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
cout << val
<< " pushed into stack successfully !\n";
}
bool isEmpty()
{
// If stack is empty return 1
return (top < 0);
}
};
int main()
{
Stack st;
cout << st.isEmpty();
return 0;
}
Java
// Java code for above approach
import java.io.*;
public class GFG {
static class Stack {
int stack[] = new int[10];
int MAX = 10;
int top;
void stack() { top = -1; }
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
System.out.println("Stack Overflow");
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
System.out.println(
val + " pushed into stack successfully !");
}
boolean isEmpty(){
return (top<=0);
}
}
public static void main(String[] args)
{
Stack st = new Stack();
System.out.println(st.isEmpty());
}
}
// This code is contributed by adityamaharshi21.
Python
class Stack:
def __init__(self):
self.stack = [0]*10
self.MAX = 10
self.top = -1
def push(self, val):
# If top is pointing to maximum size of stack
if self.top >= self.MAX - 1:
# Stack is full
print("Stack Overflow")
return
# Point top to new top
self.top += 1
# Insert new element at top of stack
self.stack[self.top] = val
print(val, "pushed into stack successfully!")
def isEmpty(self):
return (self.top < 0)
st = Stack()
print(st.isEmpty())
C#
// C# code for above approach
using System;
public class GFG {
class Stack {
int[] stack = new int[10];
int MAX = 10;
int top;
public Stack() { top = -1; }
public void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
Console.WriteLine("Stack Overflow");
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
Console.WriteLine(
val + " pushed into stack successfully !");
}
public int isEmpty() { return (top <= 0) ? 1 : 0; }
}
static public void Main()
{
// Code
Stack st = new Stack();
Console.WriteLine(st.isEmpty());
}
}
// This code is contributed by karthik.
JavaScript
// JS code for above operation
class Stack {
constructor() {
this.stack = [];
this.MAX = 10;
this.top = -1;
}
push(val) {
// If top is pointing to
// maximum size of stack
if (this.top >= this.MAX - 1) {
// Stack is full
console.log("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
console.log(val, " pushed into stack successfully !");
}
isEmpty() {
// If stack is empty return 1
return (this.top < 0);
}
};
// Driver code
let st = new Stack();
console.log(st.isEmpty());
// This code is contributed by adityamaharshi21
Complexity Analysis:
- Time Complexity: O(1), It only performs an arithmetic operation to check if the stack is empty or not.
- Auxiliary Space: O(1), It requires no extra space.
Below is the implementation of isempty() using Linked List :
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val)
{
data = val;
next = NULL;
}
};
class Stack {
public:
Node* top;
Stack() { top = NULL; }
void push(int val)
{
// Create new node temp and allocate memory in heap
Node* temp = new Node(val);
// If stack is empty
if (!top) {
top = temp;
cout << val
<< " pushed into stack successfully !\n";
return;
}
temp->next = top;
top = temp;
cout << val
<< " pushed into stack successfully !\n";
}
bool isEmpty()
{
// If top is NULL it means that
// there are no elements are in stack
return top == NULL;
}
};
int main()
{
Stack st;
cout << st.isEmpty();
return 0;
}
Java
import java.util.EmptyStackException;
class Node {
public int data;
public Node next;
public Node(int val) {
data = val;
next = null;
}
}
class Stack {
private Node top;
public Stack() {
top = null;
}
public void push(int val) {
Node temp = new Node(val);
if (top == null) {
top = temp;
System.out.println(val + " pushed into stack successfully !");
return;
}
temp.next = top;
top = temp;
System.out.println(val + " pushed into stack successfully !");
}
public boolean isEmpty() {
return top == null;
}
}
public class Main {
public static void main(String[] args) {
Stack st = new Stack();
System.out.println(st.isEmpty());
}
}
Python3
class Node:
def __init__(self, val):
self.data = val
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, val):
temp = Node(val)
if not self.top:
self.top = temp
print(val, "pushed into stack successfully!")
return
temp.next = self.top
self.top = temp
print(val, "pushed into stack successfully!")
def is_empty(self):
return self.top == None
st = Stack()
print(st.is_empty())
# This code is contributed by Vikram_Shirsat
C#
using System;
class Node
{
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Stack
{
private Node top;
public Stack()
{
top = null;
}
// Push operation to add a value to the top of the stack
public void Push(int val)
{
Node temp = new Node(val);
if (top == null)
{
top = temp;
Console.WriteLine(val + " pushed into stack successfully!");
return;
}
temp.next = top;
top = temp;
Console.WriteLine(val + " pushed into stack successfully!");
}
// Check if the stack is empty
public bool IsEmpty()
{
// If top is NULL it means that
// there are no elements are in stack
return top == null;
}
}
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
if(st.IsEmpty()) Console.WriteLine(1);
else Console.WriteLine(0);
}
}
JavaScript
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
}
push(val) {
let temp = new Node(val);
if (!this.top) {
this.top = temp;
console.log(`${val} pushed into stack successfully!`);
return;
}
temp.next = this.top;
this.top = temp;
console.log(`${val} pushed into stack successfully!`);
}
isEmpty() {
return this.top === null;
}
}
let st = new Stack();
console.log(st.isEmpty());
Complexity Analysis:
- Time Complexity: O(1), It checks if the pointer of the top pointer is Null or not. This operation takes constant time.
- Auxiliary Space: O(1), No extra space is required.
5) size():
This operation returns the current size of the stack.
Below is the implementation of size() using Array:
C++
#include <bits/stdc++.h>
using namespace std;
class Stack {
public:
int stack[10];
int MAX = 10;
int top;
Stack() { top = -1; }
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
cout << "Stack Overflow\n";
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
cout << val
<< " pushed into stack successfully !\n";
}
int size() { return top + 1; }
};
int main()
{
Stack st;
st.push(1);
st.push(2);
cout << "The size of the stack is " << st.size()
<< endl;
return 0;
}
Java
import java.util.*;
class Stack {
int[] stack;
int MAX = 10;
int top;
Stack()
{
top = -1;
stack = new int[MAX];
}
void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1) {
// Stack is full
System.out.println("Stack Overflow");
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
System.out.println(
val + " pushed into stack successfully!");
}
int size() { return top + 1; }
}
public class Main {
public static void main(String[] args)
{
Stack st = new Stack();
st.push(1);
st.push(2);
System.out.println("The size of the stack is "
+ st.size());
}
}
Python3
# Python implementation
class Stack:
stack = [0]*10 # initialize stack with size 10 and all elements 0
MAX = 10
top = -1
def push(self, val):
# If top is pointing to maximum size of stack
if self.top >= self.MAX - 1:
# Stack is full
print("Stack Overflow")
return
# Point top to new top
self.top += 1
# Insert new element at top of stack
self.stack[self.top] = val
print(f"{val} pushed into stack successfully !")
def size(self):
return self.top + 1
st = Stack()
st.push(1)
st.push(2)
print(f"The size of the stack is {st.size()}")
# This code is contributed by Vikram_Shirsat
C#
// C# code addition
using System;
// Creating a stack class.
public class Stack
{
int[] stack;
int MAX = 10;
int top;
// Initialising variables.
public Stack()
{
top = -1;
stack = new int[MAX];
}
// push element in a stack.
public void push(int val)
{
// If top is pointing to maximum size of stack
if (top >= MAX - 1)
{
// Stack is full
Console.WriteLine("Stack Overflow");
return;
}
// Point top to new top
top++;
// Insert new element at top of stack
stack[top] = val;
Console.WriteLine($"{val} pushed into stack successfully!");
}
// Find the size of stack.
public int size()
{
return top + 1;
}
}
public class GFG
{
// Driver code
public static void Main()
{
// Creating a new stack.
Stack st = new Stack();
st.push(1);
st.push(2);
// Printing the size of the stack.
Console.WriteLine($"The size of the stack is {st.size()}");
}
}
// The code is contributed by Arushi Goel.
JavaScript
// JS code for above operation
class Stack {
constructor() {
this.stack = [];
this.MAX = 10;
this.top = -1;
}
push(val) {
// If top is pointing to maximum size of stack
if (this.top >= this.MAX - 1) {
// Stack is full
console.log("Stack Overflow");
return;
}
// Point top to new top
this.top++;
// Insert new element at top of stack
this.stack[this.top] = val;
console.log(val, " pushed into stack successfully !");
}
size() { return this.top + 1; }
};
let st = new Stack;
st.push(1);
st.push(2);
console.log("The size of the stack is ", st.size());
return 0;
// This code is contributed by adityamaharshi21
Output1 pushed into stack successfully !
2 pushed into stack successfully !
The size of the stack is 2
Complexity Analysis:
- Time Complexity: O(1), because this operation just performs a basic arithmetic operation.
- Auxiliary Space: O(1) NO extra space is required to calculate the value of the top pointer.
Below is the implementation of size() using Linked List:
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val)
{
data = val;
next = NULL;
}
};
class Stack {
public:
Node* top;
Node* head;
int sizeOfStack;
Stack()
{
head = NULL;
top = NULL;
sizeOfStack = 0;
}
void push(int val)
{
// Create new node temp and
// allocate memory in heap
Node* temp = new Node(val);
sizeOfStack += 1;
// If stack is empty
if (!top) {
top = temp;
return;
}
temp->next = top;
top = temp;
}
int size() { return sizeOfStack; }
};
int main()
{
Stack st;
st.push(1);
st.push(3);
st.push(4);
cout << "Size of stack : " << st.size();
return 0;
}
Java
// Java implementation of size() using Linked List:
import java.io.*;
import java.util.*;
class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Stack {
public Node top;
public Node head;
public int sizeOfStack;
public Stack()
{
head = null;
top = null;
sizeOfStack = 0;
}
public void push(int val)
{
// Create new node temp and allocate memory in heap
Node temp = new Node(val);
sizeOfStack += 1;
// If stack is empty
if (top == null) {
top = temp;
return;
}
temp.next = top;
top = temp;
}
public int size() { return sizeOfStack; }
}
class GFG {
public static void main(String[] args)
{
Stack st = new Stack();
st.push(1);
st.push(3);
st.push(4);
System.out.println("Size of stack : " + st.size());
}
}
// This code is contributed by sankar.
Python3
# Python implementation
class Node:
def __init__(self, val):
self.data = val
self.next = None
class Stack:
def __init__(self):
self.head = None
self.top = None
self.sizeOfStack = 0
def push(self, val):
# Create new node temp and allocate memory in heap
temp = Node(val)
self.sizeOfStack += 1
# If stack is empty
if not self.top:
self.top = temp
return
temp.next = self.top
self.top = temp
def size(self):
return self.sizeOfStack
st = Stack()
st.push(1)
st.push(3)
st.push(4)
print(f"Size of stack : {st.size()}")
# This code is contributed by Vikram_Shirsat
C#
// C# implementation of size() using Linked List:
using System;
public class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
public class Stack {
public Node top;
public Node head;
public int sizeOfStack;
public Stack()
{
head = null;
top = null;
sizeOfStack = 0;
}
public void Push(int val)
{
// Create new node temp and allocate memory in heap
Node temp = new Node(val);
sizeOfStack += 1;
// If stack is empty
if (top == null) {
top = temp;
return;
}
temp.next = top;
top = temp;
}
public int Size() { return sizeOfStack; }
static public void Main()
{
// Code
Stack st = new Stack();
st.Push(1);
st.Push(3);
st.Push(4);
Console.WriteLine("Size of stack: " + st.Size());
}
}
// This code is contributed by karthik.
JavaScript
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class Stack {
constructor() {
this.head = null;
this.top = null;
this.sizeOfStack = 0;
}
push(val) {
// Create new node temp and allocate memory in heap
const temp = new Node(val);
this.sizeOfStack += 1;
// If stack is empty
if (!this.top) {
this.top = temp;
return;
}
temp.next = this.top;
this.top = temp;
}
size() {
return this.sizeOfStack;
}
}
const st = new Stack();
st.push(1);
st.push(3);
st.push(4);
console.log("Size of stack: ", st.size());
Complexity Analysis:
- Time Complexity: O(1), because the size is calculated and updated every time a push or pop operation is performed and is just returned in this function.
- Auxiliary Space: O(1), NO extra space is required to calculate the size of the stack.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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