總覺得不夠完善,先記錄下來,在使用中慢慢修改
' 隻能硬模仿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