Using a List Class


The real work of managing the links is done by the CList class. As I mentioned earlier, users never access the CLink class directly. But before we examine how CList works, let’s see how it’s used:

‘ Insert item into list
Dim list As New CList
list.Add “Bear”
list.Add “Tiger”
list.Add “Lion”
list.Add “Elephant”
list.Add “Horse”
list.Add “Dog”

This code adds some entries to the list. If you look at the list variable in the Locals window at this point, you’ll be impressed and perhaps a little surprised. The list object has a Head member that shows the first item in the list. You can expand it and expand its NextLink, and expand the NextLink of that, and so on to the end of the list. For this short list, there’s room in the Locals window to confirm that all the items are really there but not necessarily in the order you’d expect. The last item added appears at the head of the list.


Because clients don’t have access to the Locals window, they might want some methods and properties to get at the entries:

s = s & “Count: “ & list.Count & sCrLf
s = s & “Head: “ & list & sCrLf
s = s & “Item 2: “ & list(2) & sCrLf
s = s & “Item Tiger: “ & list(“Tiger”) & sCrLf

Here’s the output from these statements:

Count: 6
Head: Dog
Item 2: Horse
Item Tiger: Tiger

The string index doesn’t make much sense for this list of strings; it just returns what you already know. But it might be useful for a list of class objects:

Debug.Print list(“Tiger”).Fierceness

In this case, you are asking for the object whose default property has the value Tiger. You can also use the string index to replace an item, as follows:

s = s & “Replace Elephant with Pig” & sCrLf
list(“Elephant”) = “Pig”

The list also has a Remove method that removes either the first item (by default) or another item (specified by a string or an index) as shown below:

s = s & “Remove head: “ & list & sCrLf
list.Remove
s = s & “Remove Bear” & sCrLf
list.Remove “Bear”
s = s & “Remove 3: “ & list(3) & sCrLf
list.Remove 3

This is all fine as far as it goes, but it’s hard to tell whether the list works because there’s no way to iterate through it to see all the entries.


One way or another, you need to be able to iterate through the list. So why not just add a NextItem method to the CList class so that you can iterate through the items? Well, you could, and I did in an early implementation of CList. Originally, I based my linked list class on a C++ list in The C++ Programming Language (Addison-Wesley, 1986) by C++ creator Bjarne Stroustrup. His list had a separate iterator class, but I thought this was an unnecessary complication that I didn’t need to follow. Well, as the design progressed I began to realize why he’s a language designer and I’m a mere book author. So I’m going to start things off right with a separate CListWalker class. I think this will make sense by the time I finish, even if it doesn’t now.