Open In App

How to Compare Two Stacks in C++?

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a stack is a type of data structure where elements are inserted and removed according to the Last-In-First-Out (LIFO) principle. In this article, we will see how to compare two stacks in C++.

Example:

Input: 
stack1 = {10,20,30,40,50}
stack2 = {10,20,30,40,50}

Output:
Stacks are equal

Comparing Two Stacks in C++

To compare two std::stacks in C++ there was no direct method in STL. We had to do it manually by iterating through both stacks, popping elements, and checking their equality. But since C++20, we can use the equality and relational operators with stack to compare them. But in this article, we will only show the manual method of comparing.

Approach

  • Create two stacks, stack1, and stack2, and push elements into each stack.
  • Compare the sizes of stack1 and stack2; if they are not equal, the stacks are not equal.
  • If the sizes are equal, iterate through both stacks simultaneously, comparing the top elements at each step.
  • If any pair of corresponding elements from stack1 and stack2 are not equal, the stacks are not equal.
  • Continue this process until both stacks are empty or until an unequal pair is found.
  • If all pairs of corresponding elements are equal and both stacks are empty at the end, the stacks are considered equal. Otherwise, they are not equal.

C++ Program to Compare Two Stacks

The below example demonstrates how we can compare two stacks in C++.

C++
// C++ Program to demonstrates how we can compare two stacks
#include <iostream>
#include <stack>

using namespace std;

bool compareStacks(stack<int>& s1, stack<int>& s2)
{
    if (s1.size() != s2.size()) {
        return false;
    }

    while (!s1.empty()) {
        if (s1.top() != s2.top()) {
            return false;
        }
        s1.pop();
        s2.pop();
    }

    return true;
}

int main()
{
    stack<int> stack1, stack2;

    // Pushing elements into stack1
    stack1.push(1);
    stack1.push(2);
    stack1.push(3);

    // Pushing elements into stack2
    stack2.push(1);
    stack2.push(2);
    stack2.push(3);

    // Comparing the two stacks
    bool res = compareStacks(stack1, stack2);

    if (res) {
        cout << "Stacks are equal." << endl;
    }
    else {
        cout << "Stacks are not equal." << endl;
    }

    return 0;
}

Output
Stacks are equal.

Time Complexity: O(min(n1, n2)), where n1 and n2 are the sizes of the input stacks.
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads