Advertisement
ArXen42

CustomStack.vb

Apr 24th, 2016
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.51 KB | None | 0 0
  1.  
  2. Imports System.Collections
  3. Imports System.Collections.Generic
  4.  
  5. ''' <summary>
  6. ''' Простая реализация стека на основе массива.
  7. ''' </summary>
  8. ''' <typeparam name="T">Тип элемента</typeparam>
  9. Public NotInheritable Class CustomStack(Of T)
  10.   Public Sub New(capacity As Int32)
  11.     arr = New T(capacity - 1) {}
  12.     lastIndex = -1
  13.   End Sub
  14.  
  15.   Public Sub New()
  16.     Me.New(0)
  17.   End Sub
  18.  
  19.   Public Function Peek() As T
  20.     If lastIndex > -1 Then
  21.       Return arr(lastIndex)
  22.     Else
  23.       Throw New InvalidOperationException("Stack empty.")
  24.     End If
  25.   End Function
  26.  
  27.   Public Sub Push(value As T)
  28.     lastIndex += 1
  29.  
  30.     If arr.Length < lastIndex + 1 Then
  31.       Me.Capacity = IIf(lastIndex > 0, lastIndex * 2, 1)
  32.     End If
  33.  
  34.     arr(lastIndex) = value
  35.   End Sub
  36.  
  37.   Public Function Pop() As T
  38.     If lastIndex > -1 Then
  39.       lastIndex -= 1
  40.       Return arr(lastIndex + 1)
  41.     Else
  42.       Throw New InvalidOperationException("Stack empty.")
  43.     End If
  44.   End Function
  45.  
  46.   Public ReadOnly Property Count() As Integer
  47.     Get
  48.       Return lastIndex + 1
  49.     End Get
  50.   End Property
  51.  
  52.   Public Property Capacity() As Integer
  53.     Get
  54.       Return arr.Length
  55.     End Get
  56.     Set
  57.       If Value >= Count Then
  58.         Array.Resize(Of T)(arr, Value)
  59.       Else
  60.         Throw New ArgumentOutOfRangeException("Capacity was less than the current size.")
  61.       End If
  62.     End Set
  63.   End Property
  64.  
  65.   Private arr As T()
  66.   Private lastIndex As Integer
  67. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement