using System;
using System.Collections.Generic;
class StackRemoveDuplicates
{
public static Stack<int> RemoveDuplicatesFromStack(Stack<int> stack) {
HashSet<int> seen = new HashSet<int>();
Stack<int> uniqueStack = new Stack<int>();
while (stack.Count > 0) {
int element = stack.Pop();
if (!seen.Contains(element)) {
seen.Add(element);
uniqueStack.Push(element);
}
}
return uniqueStack;
}
private static Stack<int> InitStack(long size, int bound) {
Stack<int> stack = new Stack<int>();
Random random = new Random();
for (int i = 0; i < size; i++) {
stack.Push(random.Next(1, bound + 1)); // Random number between 1 and bound
}
return stack;
}
static void Main(string[] args)
{
Stack<int> stack = InitStack(15L, 10);
Console.WriteLine("Random Elements:");
foreach (int num in stack) {
Console.Write(num + " ");
}
Console.WriteLine();
Stack<int> uniqueStack = RemoveDuplicatesFromStack(stack);
Console.WriteLine("Remove Duplicates:");
foreach (int num in uniqueStack) {
Console.Write(num + " ");
}
Console.WriteLine();
}
}
/*
run:
Random Elements:
2 3 2 8 6 9 9 8 8 7 8 1 3 8 10
Remove Duplicates:
10 1 7 9 6 8 3 2
*/