A little more on linked list nodes

It occurred to me, after writing about linked lists yesterday, that you might want to do this:

var myList = new LinkedList.Circular();
myList.append(foo);
myList.append(bar);
myList.first = baz;

Doing that would break the list: baz does not (we assume) have correct prev and next pointers set. And so we have another use for the LinkedList.Node: you can change its data property and leave its pointers intact:

var myList = new LinkedList.Circular();
myList.append(new LinkedList.Node(foo));
myList.append(new LinkedList.Node(bar));
myList.first.data = baz;

You’ve just changed the first item in the list, but its placeholder in the list remains unchanged.

I also mentioned that you might want to use nodes if you need to include items in multiple lists: several nodes can have their data property point to the same object. But, you can also, should you wish, include the same item multiple times in the same list:

var myList = new LinkedList.Circular();
myList.append(new LinkedList.Node(foo));
myList.append(new LinkedList.Node(bar));
myList.append(new LinkedList.Node(foo));

That list has three distinct nodes, but the first and last nodes both point to foo. So you could use this, for example, to make a queue of operations where some actions need to be repeated at different points in the sequence.

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.