Topics: Linked list, C, Reference Pages: 5 (1695 words) Published: February 28, 2011
Intro
Although linked lists sounds kind of scary, don’t worry they are really easy to use once you’ve got a little practice under your belt! When I first learned this odd way of storing data, I really thought that I wouldn’t be using them again. I certainly learned differently! Linked lists form the foundation of many data storing schemes in my game! They are really nice when you don’t know how many of a data type you will need, and don’t want to waste space. They are like having a dynamically allocated string that fluctuates in size as the program runs. Before I really confuse you lets get into a better explanation! A linked list is a chain of structs or records called nodes. Each node has at least two members, one of which points to the next item or node in the list! These are defined as Single Linked Lists because they only point to the next item, and not the previous. Those that do point to both are called Doubly Linked Lists or Circular Linked Lists. According to this definition, we could have our record hold anything we wanted! The only drawback is that each record must be an instance of the same structure. This means that we couldn’t have a record with a char pointing to another structure holding a short, a char array, and a long. Again, they have to be instances of the same structure for this to work. Another cool aspect is that each structure can be located anywhere in memory, each node doesn’t have to be linear in memory! typedef struct List { long Data; List* Next; List() {Next=NULL; Data=0; } }; typedef List* ListPtr; Notice that we define a default constructor for our structure that sets Next equal to NULL. This is because we need to know when we have reached the end of our linked list. Each Next item that is NOT equal to NULL means that it is pointing to another allocated instance. If it does equal NULL, then we have reached the end of our list.

1

Starting up

We can actually add nodes in two possible places, the beginning or the end, although the standard seems to be the end. This makes our linked list act kind of like a que with the head node being the oldest and end pointing to the newest objects. This brings up an interesting subject also. How will we use our linked list? This is what makes the linked list so powerful. We could use it as a priority list where the oldest objects get a higher precedence until deleted from the list. We could also use it as a master listing of items that need to be kept track of at one time, deleting object when they need to be, without using any precedence scheme. Here’s some code that will add a node onto the end of the list, and then move the end pointer so that it really does point at the end.

2

void SLList::AddANode() {Tail->Next = new List; Tail=Tail->Next; } Here we add a node onto the end of...