#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
*/