- UID
- 5181
- 精华
- 积分
- 453
- 威望
- 点
- 宅币
- 个
- 贡献
- 次
- 宅之契约
- 份
- 最后登录
- 1970-1-1
- 在线时间
- 小时
|
本帖最后由 天马座 于 2020-11-7 23:31 编辑
众所周知VB没有指针对象,很多语言也没有指针对象,导致编写链式存储结构很麻烦,但是VB有数组,并且一般情况编写链式存储结构的数据类型的成员都是固定的完全可以使用数组实现,那么数组的索引就相当于内存地址,
比如一个树的节点可以写成如下形式Dim mem() As TreeNode
debug.print mem(p).key '索引相当于地址 mem数组相当于整个内存 那么我们只需要对数组的规模和索引进行有效的管理就可以了
如果还是不明白可以参考 算法导论 第10章 10.3 指针和对象实现
下面是我封装好的一个类,大家可以直接拿去使用,类外绑定一下数据类型就可以
手机打字有点费劲 例子就不写了,自行脑补- Private Const START_HEADER = 0
- Private header As Long, allocCount As Long, last As Long
- Private nextFree() As Long
- Private Sub Class_Initialize()
- Call clear
- End Sub
- Private Sub Class_Terminate()
- Erase nextFree
- End Sub
- Public Property Get count() As Long
- count = allocCount
- End Property
- Public Property Get capacity() As Long
- capacity = last - START_HEADER
- End Property
- Public Sub clear()
- allocCount = 0
- header = START_HEADER
- last = START_HEADER + 1
- ReDim nextFree(START_HEADER To last - 1)
- nextFree(header) = last
- End Sub
- Public Function alloc() As Long
- '分配一个自由的索引
- If header = last Then
- Call doubleCapacity
- End If
- Dim result As Long
- result = header
- header = nextFree(header)
- nextFree(result) = START_HEADER - 1
- allocCount = allocCount + 1
- alloc = result
- End Function
- Public Function free(ByVal p As Long) As Boolean
- '把索引标记成自由
- If p < START_HEADER Or p >= last Then
- free = False
- Exit Function
- End If
- If nextFree(p) >= START_HEADER Then
- free = False
- Exit Function
- End If
- nextFree(p) = header
- header = p
- allocCount = allocCount - 1
- free = True
- End Function
- Private Sub doubleCapacity()
- last = START_HEADER + (last - START_HEADER) * 2
- ReDim Preserve nextFree(START_HEADER To last - 1)
- Dim i As Long
- For i = header To last - 1
- nextFree(i) = i + 1
- Next
- End Sub
复制代码 |
|