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
'
'