Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to remove duplicates from a stack in C++

1 Answer

0 votes
#include <iostream>
#include <stack>
#include <unordered_set>
#include <random>

// Initialize a stack with random integers
std::stack<int> InitStack(size_t size, int bound) {
    std::stack<int> stack;
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(1, bound);

    for (size_t i = 0; i < size; ++i) {
        stack.push(dist(gen));
    }

    return stack;
}

// Remove duplicates from a stack (preserving last occurrence)
std::stack<int> RemoveDuplicatesFromStack(std::stack<int> stack) {
    std::unordered_set<int> seen;
    std::stack<int> uniqueStack;

    while (!stack.empty()) {
        int element = stack.top();
        stack.pop();
        if (seen.find(element) == seen.end()) {
            seen.insert(element);
            uniqueStack.push(element);
        }
    }

    // Reverse to restore original order of last occurrences
    std::stack<int> finalStack;
    while (!uniqueStack.empty()) {
        finalStack.push(uniqueStack.top());
        uniqueStack.pop();
    }

    return finalStack;
}

// Helper to print stack contents
void PrintStack(std::stack<int> stack) {
    std::vector<int> temp;
    while (!stack.empty()) {
        temp.push_back(stack.top());
        stack.pop();
    }
    for (auto it = temp.rbegin(); it != temp.rend(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
}

int main() {
    std::stack<int> stack = InitStack(15, 10);

    std::cout << "Random Elements:\n";
    PrintStack(stack);

    std::stack<int> uniqueStack = RemoveDuplicatesFromStack(stack);

    std::cout << "Remove Duplicates:\n";
    PrintStack(uniqueStack);
}

  
  
/*
run:
  
Random Elements:
6 8 8 1 7 1 5 1 1 8 7 6 3 4 8 
Remove Duplicates:
5 1 7 6 3 4 8 
  
*/

 



answered Oct 11, 2025 by avibootz

Related questions

1 answer 55 views
1 answer 261 views
1 answer 64 views
2 answers 155 views
2 answers 181 views
1 answer 55 views
1 answer 54 views
...