将变量设置为列表中的下一个实例不起作用

时间:2017-07-10 22:29:17

标签: vba excel-vba linked-list excel

背景信息:我正在编写 Dijkstra的最短路径算法,只是为了练习基本模式,我已阅读有关的教程。

我遇到了一个有问题的情况。经过长时间的调试后,我发现了这个问题。

这是一个缩小版本,显示问题(已评论):

Option Explicit

Private Sub btnSolution_Click()
    Dim N As Integer: N = 3

    'Creating one list with the first cell as head
    Dim list As New model_linked_list
    Set list.next_cell = Nothing

    'Creates list 1..N
    Dim i As Integer: i = N
    Do While i > 0
        'Creates the next cell adding to the start (after the head-cell)
        Dim cell As New model_linked_list
        cell.city = i
        Set cell.next_cell = list.next_cell

        'Update head-cell
        Set list.next_cell = cell
        i = i - 1
    Loop

    'All good till here, but when I try to loop over the list:

    Dim item As model_linked_list
    Set item = list.next_cell

    'You will to set a breakpoint in this line to avoid infinite loop
    Do While Not item Is Nothing

        MsgBox item.city 'Always shows "1"

        'This is the problematic line
        Set item = item.next_cell 'It seems like it does nothing, literally
    Loop

End Sub

enter image description here

我的model_linked_list只是:

Option Explicit

Public city As Integer
Public next_cell As model_linked_list

说明一下,上面的代码应该只创建一个这样的列表:

enter image description here

当我尝试转到列表中的下一个单元格时,Set似乎无效。有没有人见过这个?如何解决它?

提前致谢。

1 个答案:

答案 0 :(得分:2)

你的错误在这里:

Dim cell As New model_linked_list

将其更改为:

Dim cell As model_linked_list
Set cell = New model_linked_list

简而言之,对于Dim cell As New model_linked_list" New" 运算符只执行了一次,因此您在所有迭代中操作同一个对象。