Setting a variable to the next instance in the list does not work
Context: I am coding Dijkstra's shortest path algorithm to practice the basic patterns I read in the tutorials on excel-vba...
I am facing a problem. After a lot of debugging, I found the problem.
Here is a mini version that shows the problem (commented):
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
My is model_linked_list
simple:
Option Explicit
Public city As Integer
Public next_cell As model_linked_list
To illustrate, the above code should simply create one list like this:
It Set
just doesn't seem to work when I try to navigate to the next cell in the list. Has anyone seen this before? How do I get around this?
Thanks in advance.
source to share
Your error is here:
Dim cell As New model_linked_list
change it to:
Dim cell As model_linked_list
Set cell = New model_linked_list
In short, Dim cell As New model_linked_list
the "New" statement was executed only once, so you were manipulating the same object in all your iterations.
source to share