Implementing a List Class
There are many ways to implement linked lists, but I chose one of the most simple. Don’t assume, however, that the list will be obvious. The simple class you see before you went through a lot of iterations and a lot of testing to reach its current state.
The CList class has the following private members:
Private lnkHead As CLink
Private c As Long
The lnkHead member is what makes the list work. The c member is just for counting the members for the Count property. The lnkHead member is the only access to the list; in addition, all new members must be added here. It’s also the only access the CLinkWalker will have. The following Friend property makes the Head available to cooperating classes:
‘ Make data structure available to cooperating classes
Friend Property Get Head() As CLink
Set Head = lnkHead
End Property
The Add method should give you a feel for the implementation:
‘ Insert at head of list
Sub Add(vItem As Variant)
‘ Create temporary link with new value
Dim lnkTmp As CLink
Set lnkTmp = New CLink
If IsObject(vItem) Then
Set lnkTmp.Item = vItem
Else
lnkTmp.Item = vItem
End If
‘ Point it where previous head pointed
Set lnkTmp.NextLink = lnkHead
‘ Attach it to front
Set lnkHead = lnkTmp
‘ lnkTmp temporary goes out of scope and disappears
c = c + 1
End Sub
If this code seems confusing, try stepping through it in the TCOLLECT.VBG project. Put watches on the lnkTmp and lnkHead object variables. Watch as the first item is added to the list, and keep watching as more items are added.
I could show you more methods and properties, but they wouldn’t make sense until you understand the CListWalker class.