Overload == operator for Stack
Last Updated :
13 Apr, 2023
Stack is a linear data structure that works in a model of LIFO ( last in first out ). In which, the element pushed at last will be deleted at first.
Insertion and deletion will happen on the same end. A real-life example of a stack would be a stack of books, a stack of plates, etc. The Insertion deletion diagram will look like this :
Stack insertion And deletion or push, pop operationOverload '==' operator to check equality of size:
Approach: The task for overloading '==' operator can be performed as shown below:
- Initialize two stacks stk1 and stk2 of size N and check if size is equal or not.
- Then Implement a friend method out of class because.
- In the overloaded function for the operator, check if the size of stack1 is equal to stack2 then return true else return false.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
class Stack {
// Properties of stack
int* stk;
int length;
int size;
public:
// One argument constructor of stack .
Stack(int size)
{
this->size = size;
this->length = 0;
this->stk = new int[size];
}
// Getter method of stack
int getSize() { return this->size; }
// Push method of stack which push data at end
void push(int val)
{
if (length < size)
stk[length++] = val;
else
cout << "\nstack is full\n";
}
// Friend method declaration for
// == operator overloading
friend bool operator==(Stack&, Stack&);
};
// As friend method is not the part of stack class,
// so we are implementing it outside.
bool operator==(Stack& stk1, Stack& stk2)
{
// If size of stk1 is equal to size of stk2,
// then return true else false;
return (stk1.getSize() == stk2.getSize());
}
// Driver code
int main()
{
Stack stk1(10), stk2(10);
if (stk1 == stk2) {
cout << "Both stk1 and stk2 are equal (size).\n";
}
else {
cout << "stk1 and stk2 are not equal (size).\n";
}
return 0;
}
Java
import java.util.*;
class Stack {
// Properties of stack
private int[] stk;
private int length;
private int size;
// One argument constructor of stack .
public Stack(int size) {
this.size = size;
this.length = 0;
this.stk = new int[size];
}
// Getter method of stack
public int getSize() {
return this.size;
}
// Push method of stack which push data at end
public void push(int val) {
if (length < size)
stk[length++] = val;
else
System.out.println("\nstack is full\n");
}
// Friend method declaration for
// == operator overloading
public static boolean equals(Stack stk1, Stack stk2) {
// If size of stk1 is equal to size of stk2,
// then return true else false;
return (stk1.getSize() == stk2.getSize());
}
}
// Driver code
public class Main {
public static void main(String[] args) {
Stack stk1 = new Stack(10);
Stack stk2 = new Stack(10);
if (Stack.equals(stk1, stk2)) {
System.out.println("Both stk1 and stk2 are equal (size).");
} else {
System.out.println("stk1 and stk2 are not equal (size).");
}
}
}
Python3
class Stack:
# Constructor
def __init__(self, size):
self.size = size
self.length = 0
self.stk = [0] * size
# Getter method for size
def getSize(self):
return self.size
# Method for pushing element to the stack
def push(self, val):
if self.length < self.size:
self.stk[self.length] = val
self.length += 1
else:
print("stack is full")
# Overloading == operator
def __eq__(self, other):
# If size of self is equal to size of other, return True, else False
return self.getSize() == other.getSize()
# Main function
def main():
stk1 = Stack(10)
stk2 = Stack(10)
if stk1 == stk2:
print("Both stk1 and stk2 are equal (size).")
else:
print("stk1 and stk2 are not equal (size).")
if __name__ == '__main__':
main()
# This code is contributed by Vikram_Shirsat
C#
using System;
public class Stack
{
private int size;
private int length;
private int[] stk;
// Constructor
public Stack(int size)
{
this.size = size;
this.length = 0;
this.stk = new int[size];
}
// Getter method for size
public int GetSize()
{
return size;
}
// Method for pushing element to the stack
public void Push(int val)
{
if (length < size)
{
stk[length] = val;
length++;
}
else
{
Console.WriteLine("stack is full");
}
}
// Overloading == operator
public static bool operator ==(Stack s1, Stack s2)
{
// If size of s1 is equal to size of s2, return True, else False
return s1.GetSize() == s2.GetSize();
}
public static bool operator !=(Stack s1, Stack s2)
{
return !(s1 == s2);
}
}
public class Program
{
public static void Main()
{
Stack stk1 = new Stack(10);
Stack stk2 = new Stack(10);
if (stk1 == stk2)
{
Console.WriteLine("Both stk1 and stk2 are equal (size).");
}
else
{
Console.WriteLine("stk1 and stk2 are not equal (size).");
}
}
}
JavaScript
class Stack {
constructor(size) {
// Properties of stack
this.stk = new Array(size);
this.length = 0;
this.size = size;
}
// Getter method of stack
getSize() {
return this.size;
}
// Push method of stack which push data at end
push(val) {
if (this.length < this.size) {
this.stk[this.length++] = val;
} else {
console.log("\nstack is full\n");
}
}
// Friend method declaration for
// == operator overloading
static isEqual(stk1, stk2) {
// If size of stk1 is equal to size of stk2,
// then return true else false;
return stk1.getSize() === stk2.getSize();
}
}
// Driver code
const stk1 = new Stack(10);
const stk2 = new Stack(10);
if (Stack.isEqual(stk1, stk2)) {
console.log("Both stk1 and stk2 are equal (size).\n");
} else {
console.log("stk1 and stk2 are not equal (size).\n");
}
OutputBoth stk1 and stk2 are equal (size).
Time Complexity : O(1), because all the operations performed are basic stack operations that take a constant amount of time, regardless of the input size.
Auxiliary Space : O(N), where N is the maximum size of the stack.
Overload '==' operator for checking if elements of both stacks are equal:
- In this case in the overloaded function for == operator:
- If both stacks don't have the same size, then return false.
- Check each element of both stacks and if both the stacks have the same elements then it should return true else false.
- To check that, run a loop till both are empty and compare the top elements.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
class Stack {
// Properties of stack
int* stk;
int length;
int size;
public:
// One argument constructor of stack
Stack(int size)
{
this->size = size;
this->length = 0;
this->stk = new int[size];
}
// Getter method of stack
int getSize() { return this->size; }
// Return the number of element present in stack
int getLength() { return this->length; }
// Return the iterator of first element
int* begin() { return this->stk; }
// Push method of stack which push data at end
void push(int val)
{
if (length < size)
stk[length++] = val;
else
cout << "\nstack is full\n";
}
// Friend method declaration for
// == operator overloading
friend bool operator==(Stack&, Stack&);
};
// As friend method is not the part of stack class,
// so we are implementing it outside.
bool operator==(Stack& stk1, Stack& stk2)
{
// If size of stk1 is equal to size of stk2,
// then return true else false;
int lenghtOfStack_1 = stk1.getLength();
int lenghtOfStack_2 = stk2.getLength();
// If length of stk1 is not equal to stk2
// means both stacks have different number
// of elements, for that return false;
if (lenghtOfStack_1 != lenghtOfStack_2) {
return false;
}
// As both the stack have same length,
// then we can use any one of them
for (int i = 0; i < lenghtOfStack_1; i++) {
// Here, we are checking if any time stk1 value
// is not equal to stk2 value. return false.
if (stk1.begin()[i] != stk2.begin()[i]) {
return false;
}
}
// If above loop does not return false value,
// means, both the stacks have same elements
// so, we are returning true here.
return true;
}
// Driver code
int main()
{
Stack stk1(10), stk2(10);
// Pushing elements into the stacks
for (int i = 0; i < 5; i++) {
stk1.push(i);
stk2.push(i);
}
// Checking if both stacks are equal are not.
if (stk1 == stk2) {
cout << "Both stk1 and stk2 are equal.\n";
}
else {
cout << "stk1 and stk2 are not equal.\n";
}
return 0;
}
Java
import java.util.Arrays;
class Stack {
// Properties of stack
private int[] stk;
private int length;
private int size;
// One argument constructor of stack
Stack(int size) {
this.size = size;
this.length = 0;
this.stk = new int[size];
}
// Getter method of stack
int getSize() {
return this.size;
}
// Return the number of element present in stack
int getLength() {
return this.length;
}
// Return the iterator of first element
int[] begin() {
return this.stk;
}
// Push method of stack which push data at end
void push(int val) {
if (length < size)
stk[length++] = val;
else
System.out.println("\nstack is full\n");
}
// Overriding the equals() method
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Stack)) {
return false;
}
Stack otherStack = (Stack) obj;
// If size of current stack is not equal to size of other stack,
// then return false;
if (this.length != otherStack.length) {
return false;
}
// As both the stacks have same length,
// then we can use any one of them
for (int i = 0; i < this.length; i++) {
// Here, we are checking if any time current stack value
// is not equal to other stack value. return false.
if (this.stk[i] != otherStack.stk[i]) {
return false;
}
}
// If above loop does not return false value,
// means, both the stacks have same elements
// so, we are returning true here.
return true;
}
}
// Driver code
public class Main {
public static void main(String[] args) {
Stack stk1 = new Stack(10);
Stack stk2 = new Stack(10);
// Pushing elements into the stacks
for (int i = 0; i < 5; i++) {
stk1.push(i);
stk2.push(i);
}
// Checking if both stacks are equal are not.
if (stk1.equals(stk2)) {
System.out.println("Both stk1 and stk2 are equal.");
} else {
System.out.println("stk1 and stk2 are not equal.");
}
}
}
Python3
# Python equivalent of the given code
class Stack:
# Properties of stack
stk = []
length = 0
size = 0
# One argument constructor of stack
def __init__(self, size):
self.size = size
self.length = 0
self.stk = [0] * size
# Getter method of stack
def getSize(self):
return self.size
# Return the number of element present in stack
def getLength(self):
return self.length
# Push method of stack which push data at end
def push(self, val):
if self.length < self.size:
self.stk[self.length] = val
self.length += 1
else:
print("stack is full")
# As friend method is not the part of stack class,
# so we are implementing it outside.
def __eq__(stk1, stk2):
# If size of stk1 is equal to size of stk2,
# then return true else false;
lenghtOfStack_1 = stk1.getLength()
lenghtOfStack_2 = stk2.getLength()
# If length of stk1 is not equal to stk2
# means both stacks have different number
# of elements, for that return false;
if lenghtOfStack_1 != lenghtOfStack_2:
return False
# As both the stack have same length,
# then we can use any one of them
for i in range(lenghtOfStack_1):
# Here, we are checking if any time stk1 value
# is not equal to stk2 value. return false.
if stk1.stk[i] != stk2.stk[i]:
return False
# If above loop does not return false value,
# means, both the stacks have same elements
# so, we are returning true here.
return True
# Driver code
if __name__ == "__main__":
stk1 = Stack(10)
stk2 = Stack(10)
# Pushing elements into the stacks
for i in range(5):
stk1.push(i)
stk2.push(i)
# Checking if both stacks are equal are not.
if stk1 == stk2:
print("Both stk1 and stk2 are equal.")
else:
print("stk1 and stk2 are not equal.")
# This code is contributed by Vikram_Shirsat
C#
// C# code to implement the approach
using System;
class Stack {
// Properties of stack
private int[] stk;
private int length;
private int size;
// One argument constructor of stack
public Stack(int size)
{
this.size = size;
this.length = 0;
this.stk = new int[size];
}
// Getter method of stack
public int GetSize() { return this.size; }
// Return the number of element present in stack
public int GetLength() { return this.length; }
// Return the iterator of first element
public int[] Begin() { return this.stk; }
// Push method of stack which push data at end
public void Push(int val)
{
if (length < size) {
stk[length++] = val;
}
else {
Console.WriteLine("\nstack is full\n");
}
}
// Friend method declaration for
// == operator overloading
public static bool operator == (Stack stk1, Stack stk2)
{
// If size of stk1 is equal to size of stk2,
// then return true else false;
int lengthOfStack_1 = stk1.GetLength();
int lengthOfStack_2 = stk2.GetLength();
// If length of stk1 is not equal to stk2
// means both stacks have different number
// of elements, for that return false;
if (lengthOfStack_1 != lengthOfStack_2) {
return false;
}
// As both the stack have same length,
// then we can use any one of them
for (int i = 0; i < lengthOfStack_1; i++) {
// Here, we are checking if any time stk1 value
// is not equal to stk2 value. return false.
if (stk1.Begin()[i] != stk2.Begin()[i]) {
return false;
}
}
// If above loop does not return false value,
// means, both the stacks have same elements
// so, we are returning true here.
return true;
}
public static bool operator != (Stack stk1, Stack stk2)
{
return !(stk1 == stk2);
}
}
// Driver code
class Program {
static void Main(string[] args)
{
Stack stk1 = new Stack(10);
Stack stk2 = new Stack(10);
// Pushing elements into the stacks
for (int i = 0; i < 5; i++) {
stk1.Push(i);
stk2.Push(i);
}
// Checking if both stacks are equal are not.
if (stk1 == stk2) {
Console.WriteLine(
"Both stk1 and stk2 are equal.");
}
else {
Console.WriteLine(
"stk1 and stk2 are not equal.");
}
}
}
JavaScript
// JavaScript code to implement the approach
class Stack {
// Properties of stack
constructor(size) {
this.stk = new Array(size);
this.length = 0;
this.size = size;
}
// Getter method of stack
getSize() {
return this.size;
}
// Return the number of element present in stack
getLength() {
return this.length;
}
// Return the iterator of first element
begin() {
return this.stk;
}
// Push method of stack which push data at end
push(val) {
if (this.length < this.size) {
this.stk[this.length++] = val;
} else {
console.log("\nstack is full\n");
}
}
}
// Friend method declaration for
// == operator overloading
function equals(stk1, stk2) {
// If size of stk1 is equal to size of stk2,
// then return true else false;
let lengthOfStack_1 = stk1.getLength();
let lengthOfStack_2 = stk2.getLength();
// If length of stk1 is not equal to stk2
// means both stacks have different number
// of elements, for that return false;
if (lengthOfStack_1 !== lengthOfStack_2) {
return false;
}
// As both the stack have same length,
// then we can use any one of them
for (let i = 0; i < lengthOfStack_1; i++) {
// Here, we are checking if any time stk1 value
// is not equal to stk2 value. return false.
if (stk1.begin()[i] !== stk2.begin()[i]) {
return false;
}
}
// If above loop does not return false value,
// means, both the stacks have same elements
// so, we are returning true here.
return true;
}
// Driver code
let stk1 = new Stack(10);
let stk2 = new Stack(10);
// Pushing elements into the stacks
for (let i = 0; i < 5; i++) {
stk1.push(i);
stk2.push(i);
}
// Checking if both stacks are equal are not.
if (equals(stk1, stk2)) {
console.log("Both stk1 and stk2 are equal.\n");
} else {
console.log("stk1 and stk2 are not equal.\n");
}
// This code is contributed by rutikbhosale
OutputBoth stk1 and stk2 are equal.
Related Articles:
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read