天天看点

vba 队列实现

总觉得不够完善,先记录下来,在使用中慢慢修改

' 只能硬模仿java

Private ne As Node

'只搜集ID
Private item As Variant


Property Let letNext(ByRef n As Node)
    Set ne = n
End Property

Property Let letItem(ByRef i As Variant)
    assign item, i
End Property

Property Get getNext()
 Set getNext = ne
End Property

Property Get getItem()
    assign getItem, item
End Property


Private Sub assign(ByRef x, ByVal y)

    If IsObject(y) Then
        Set x = y
    Else
        x = y
    End If

End Sub

           
' 队列实现,FIFO模式

' 一直都是哨兵节点
Private head As Node

' 指向尾节点
Private last As Node

' 队列数量
Private n As Integer

'哨兵节点
Private emptyNode As New Node


' 勉强当构造函数使用
Private Sub class_initialize()

    Set head = emptyNode
    Set last = emptyNode
    n = 0
End Sub


Public Function isEmpty() As Boolean
    isEmpty = head.getNext Is Nothing
End Function

Public Property Get size() As Integer
    size = n
End Property

'获取首部元素,即最先进入队列的元素,但是并不移除,仅仅查看
Public Function peek() As String
    If isEmpty() Then Err.Raise 404, "Queue.peek", "请先添加在查看"
    
    peek = head.getNext.getItem
    
End Function

'添加元素
Public Sub enqueue(ByRef s As Variant)
' 添加元素应该从尾部添加
    Dim newNode As New Node
    
    newNode.letItem = s
    
    last.letNext = newNode
    
    assign last, newNode
    
    n = n + 1

End Sub

'获取应该出列的元素,并删除其元素
Public Function dequeue() As Variant
    
    Dim first As Node
    
    
    assign first, head.getNext
    
    assign dequeue, first.getItem

     head.letNext = first.getNext
    
    n = n - 1
    
    ' 如果全部取出,必须回归到稳定状态,即初始化状态
    ' 思考:有没有一种办法,避免判断,可以借用哨兵节点
    If isEmpty() Then assign last, emptyNode
    
End Function

Public Function hasNext() As Boolean
    hasNext = Not isEmpty()
End Function

Private Sub assign(ByRef x, ByVal y)

    If IsObject(y) Then
        Set x = y
    Else
        x = y
    End If

End Sub





           

继续阅读