VBA实现数据结构中的栈类
数据结构中栈(stack)是一种比较重要的数据结构,这里给出一个使用VBA实现的栈的类模块,代码的一些说明如下:
StackItem类:类似于关联节点,包含了元素数据和一个另一节点的引用(类似于指针)
Stack类:包含了一些栈操作函数
Push:元素压栈
Pop:元素出栈
StackTop:返回栈顶元素
StackEmpty:检查栈是否为空
StackDump:转为字符串显示
Class_Initialize:栈初始化
StackItem类模块源代码
Option Explicit Public Value As Variant Public NextItem As StackItem
Stack类模块源代码
Option Explicit
Private Top As StackItem
Public Property Get StackEmpty() As Boolean
On Error Resume Next
StackEmpty = (Top Is Nothing)
End Property
Public Property Get StackTop() As Variant
On Error Resume Next
If StackEmpty Then
StackTop = Null
Else
StackTop = Top.Value
End If
End Property
Private Sub Class_Initialize()
On Error Resume Next
Set Top = Nothing
End Sub
Public Sub Push(ByVal var As Variant)
On Error Resume Next
Dim newTop As New StackItem
newTop.Value = var
Set newTop.NextItem = Top
Set Top = newTop
End Sub
Public Function Pop() As Variant
On Error Resume Next
If Not StackEmpty Then
Pop = Top.Value
Set Top = Top.NextItem
End If
End Function
Public Function StackDump(Optional ByVal delim As String) As String
On Error Resume Next
Dim dump As String
Dim item As New StackItem
Set item = Top
dump = delim & item.Value
Do While Not item.NextItem Is Nothing
Set item = item.NextItem
dump = dump & delim & item.Value
Loop
StackDump = Right(dump, Len(dump) - 2)
End Function


