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
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 52 views
2 answers 75 views
2 answers 287 views
1 answer 55 views
1 answer 53 views
1 answer 51 views
2 answers 127 views
127 views asked Mar 19, 2023 by avibootz
...