Stack: Difference between revisions

1,498 bytes added ,  12 years ago
VBA
(VBA)
Line 2,091:
you
me</lang>
 
=={{header|VBA}}==
Define a class Stack in a class module with that name.
<lang vb>
'Simple Stack class
 
'uses a dynamic array of Variants to stack the values
'has read-only property "Size"
'and methods "Push", "Pop", "IsEmpty"
 
Private myStack()
Private myStackHeight As Integer
 
'method Push
Public Function Push(aValue)
'increase stack height
myStackHeight = myStackHeight + 1
ReDim Preserve myStack(myStackHeight)
myStack(myStackHeight) = aValue
End Function
 
'method Pop
Public Function Pop()
'check for nonempty stack
If myStackHeight > 0 Then
Pop = myStack(myStackHeight)
myStackHeight = myStackHeight - 1
Else
MsgBox "Pop: stack is empty!"
End If
End Function
 
'method IsEmpty
Public Function IsEmpty() As Boolean
IsEmpty = (myStackHeight = 0)
End Function
 
'property Size
Property Get Size() As Integer
Size = myStackHeight
End Property
</lang>
 
Usage example:
<lang vb>
'stack test
Public Sub stacktest()
Dim aStack As New Stack
With aStack
'push and pop some value
.Push 45
.Push 123.45
.Pop
.Push "a string"
.Push "another string"
.Pop
.Push Cos(0.75)
Debug.Print "stack size is "; .Size
While Not .IsEmpty
Debug.Print "pop: "; .Pop
Wend
Debug.Print "stack size is "; .Size
'try to continue popping
.Pop
End With
End Sub
</lang>
 
Output:
<pre>
stacktest
stack size is 3
pop: 0,731688868873821
pop: a string
pop: 45
stack size is 0
</pre>
(after wich a message box will pop up)
 
=={{header|VBScript}}==
Anonymous user