Option Explicit
'定義堆棧的結構
Public Type StackStruct
Size As Integer '當前Stack中元素的個數
Pointer As Integer '指向Stack中棧頂的指針
MaxElementCount As Integer 'Stack中可以放入的元素的個數
Element() As Integer 'Stack中用於放置元素的數組
End Type
'根椐用戶指定的StackSize來創建一個堆棧
Public Function CreateStack(StackSize As Integer) As StackStruct
Dim h As StackStruct
h.Pointer = -1
h.Size = 0
h.MaxElementCount = StackSize
ReDim h.Element(StackSize - 1) As Integer
CreateStack = h
End Function
'判定堆棧是否為空
Public Function StackEmpty(h As StackStruct) As Boolean
StackEmpty = (h.Pointer = -1)
End Function
'判定堆棧是否己滿
Public Function StackFull(h As StackStruct) As Boolean
StackFull = (h.Size = h.MaxElementCount)
End Function
'將元素Ikey壓入堆棧
Public Function Push(ByRef h As StackStruct, Ikey As Integer) As Boolean
'若堆棧己滿,則返回False
If StackFull(h) Then Push = False: Exit Function
h.Pointer = h.Pointer + 1
h.Element(h.Pointer) = Ikey
h.Size = h.Size + 1
End Function
'將元素彈出堆棧
'若己棧,則返回False
Public Function Pop(ByRef h As StackStruct) As Variant
If StackEmpty(h) Then
Pop = False
Else
Pop = h.Element(h.Pointer)
h.Pointer = h.Pointer - 1
h.Size = h.Size - 1
End If
End Function