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 VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class StackRemoveDuplicates
    Public Shared Function RemoveDuplicatesFromStack(ByVal stack As Stack(Of Integer)) As Stack(Of Integer)
        Dim seen As HashSet(Of Integer) = New HashSet(Of Integer)()
        Dim uniqueStack As Stack(Of Integer) = New Stack(Of Integer)()

        While stack.Count > 0
            Dim element As Integer = stack.Pop()

            If Not seen.Contains(element) Then
                seen.Add(element)
                uniqueStack.Push(element)
            End If
        End While

        Return uniqueStack
    End Function

    Private Shared Function InitStack(ByVal size As Long, ByVal bound As Integer) As Stack(Of Integer)
        Dim stack As Stack(Of Integer) = New Stack(Of Integer)()
        Dim random As Random = New Random()

        For i As Integer = 0 To size - 1
            stack.Push(random.Next(1, bound + 1))
        Next

        Return stack
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim stack As Stack(Of Integer) = InitStack(15L, 10)
        Console.WriteLine("Random Elements:")

        For Each num As Integer In stack
            Console.Write(num & " ")
        Next

        Console.WriteLine()
        Dim uniqueStack As Stack(Of Integer) = RemoveDuplicatesFromStack(stack)
        Console.WriteLine("Remove Duplicates:")

        For Each num As Integer In uniqueStack
            Console.Write(num & " ")
        Next

        Console.WriteLine()
    End Sub
End Class



' run:
'
' Random Elements:
' 10 4 4 8 2 9 1 5 2 2 7 4 5 7 6 
' Remove Duplicates:
' 6 7 5 1 9 2 8 4 10 
'
'

 



answered Oct 11, 2025 by avibootz

Related questions

2 answers 99 views
2 answers 150 views
1 answer 173 views
1 answer 57 views
1 answer 55 views
1 answer 52 views
...