VBA 单链表

链表很重要,可以看做其他复杂数据结构的基础。

首先需要建立一个结点,这个结点是一个类,每个节点中包含数据和指向下一个结点的变量。建立如下代码

建立链表类,这个类包含头部结点变量,当前结点变量,还有结点的个数,代码如下

定位函数,我们要获取或者修改某一个结点,必须把pCurrent变量指向这个结点。

添加代码如下

添加结点代码

删除结点代码

获取结点值

至此一个简单的链表实现了

具体代码如下

结点类代码

Option Explicit

 

Public data As String ‘数据

Public pNext As Node ‘引用,指向下一个接点

 

‘构造函数

Private Sub Class_Initialize()

data = “”

Set pNext = Nothing

End Sub

 

‘析构函数

Private Sub Class_Terminate()

Set pNext = Nothing

End Sub

链表类代码

Option Explicit

 

Public pHead As Node

Public pCurrent As Node

Public intSize As Integer

 

Private Sub Class_Initialize()

Set pHead = New Node

Set pCurrent = pHead

End Sub

 

Private Sub Class_Terminate()

Set pHead = Nothing

Set pCurrent = Nothing

End Sub

 

Public Sub index(i As Integer)

Dim j As Integer

If i < -1 Or i > intSize – 1 Then

MsgBox “Parameter out of range”

Exit Sub

End If

Set pCurrent = pHead

j = -1

If i = -1 Then

Exit Sub

End If

Do While j < i

Set pCurrent = pCurrent.pNext

j = j + 1

Loop

End Sub

 

Public Sub insert(i As Integer, strData As String)

If i < -1 Or i > intSize Then

MsgBox “Parameter out of range”

Exit Sub

End If

Dim j As Integer

Dim p As Node

Call index(i – 1)

Set p = New Node

p.data = strData

Set p.pNext = pCurrent.pNext

Set pCurrent.pNext = p

intSize = intSize + 1

Set p = Nothing

End Sub

 

Public Sub delete(i As Integer)

If intSize = 0 Then

MsgBox “Empty list”

Exit Sub

End If

If i < -1 Or i > intSize – 1 Then

MsgBox “Parameter out of range”

Exit Sub

End If

Call index(i – 1)

Set pCurrent.pNext = pCurrent.pNext.pNext

intSize = intSize – 1

End Sub

 

Public Function getData(i As Integer) As String

If i < -1 Or i > intSize – 1 Then

MsgBox “Parameter out of range”

Exit Function

End If

Call index(i)

getData = pCurrent.data

End Function

我们在窗口中看一看这个链表的使用

参考代码如下

Option Explicit

 

Dim List1 As LinkList

 

Private Sub CommandButton1_Click()

Set List1 = New LinkList

Dim i As Integer

For i = 0 To 50

Call List1.insert(i, CStr(Rnd * 100))

Next i

For i = 0 To 50

Me.ListBox1.AddItem (List1.getData(i))

Next i

End Sub

这个代码只是示例学习用的,还可以改进的,比如intSize变量可以做属性封装,只允许读取不允许写入,index函数应该定义成私有函数,这里就不再讨论了。

徐大军

发表评论

电子邮件地址不会被公开。 必填项已用*标注