How to remove duplicates from a stack in C#

1 Answer

0 votes
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 

*/

 



answered Oct 11, 2025 by avibootz

Related questions

1 answer 59 views
2 answers 103 views
1 answer 68 views
1 answer 69 views
1 answer 71 views
2 answers 156 views
156 views asked Mar 19, 2023 by avibootz
2 answers 148 views
...