how to delete repeated element in stack c++

To delete repeated elements in a stack in C++, you can follow these steps:

  1. Create an empty stack and an empty set to keep track of the elements.
  2. Iterate through the original stack.
  3. For each element in the original stack, check if it is already present in the set.
  4. If the element is not present in the set, push it onto the new stack and add it to the set.
  5. Finally, assign the new stack to the original stack to replace it with the updated version.

Here's the code that implements the above steps:

#include <iostream>
#include <stack>
#include <unordered_set>

void deleteRepeatedElements(std::stack<int>& originalStack) {
    std::stack<int> newStack;
    std::unordered_set<int> elementsSet;

    while (!originalStack.empty()) {
        int currentElement = originalStack.top();
        originalStack.pop();

        if (elementsSet.find(currentElement) == elementsSet.end()) {
            newStack.push(currentElement);
            elementsSet.insert(currentElement);
        }
    }

    originalStack = newStack;
}

int main() {
    std::stack<int> stack;

    // Push elements into the stack
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(2);
    stack.push(4);
    stack.push(3);

    std::cout << "Original Stack:" << std::endl;
    while (!stack.empty()) {
        std::cout << stack.top() << " ";
        stack.pop();
    }

    deleteRepeatedElements(stack);

    std::cout << "\nStack after deleting repeated elements:" << std::endl;
    while (!stack.empty()) {
        std::cout << stack.top() << " ";
        stack.pop();
    }

    return 0;
}

This code first creates an original stack and pushes some elements onto it. Then, the deleteRepeatedElements function is called to delete the repeated elements. Finally, the updated stack is printed to verify that the repeated elements have been removed.