Assume we have the following array:
0 |
1 |
2 |
3 |
5 |
8 |
13 |
21 |
34 |
55 |
Now we’d like to insert another 1 between the first two elements. First create a new dynamic array with enough space.
Then copy the data in:
0 |
1 |
2 |
3 |
5 |
8 |
13 |
21 |
34 |
55 |
And finally put the new value in the free space provided.
0 |
1 |
1 |
2 |
3 |
5 |
8 |
13 |
21 |
34 |
55 |
How about if we separate all the elements from each other. (Note, we can't really do this with an array.)
0 |
1 |
2 |
3 |
5 |
8 |
13 |
21 |
34 |
55 |
Now its easy to insert a new element in between.
0 |
1 |
1 |
2 |
3 |
5 |
8 |
13 |
21 |
34 |
55 |
But there’s no connection between the boxes. We can’t move from one to another as we can with an array. We must put back some form of connection.
0 |
→ |
1 |
→ |
1 |
→ |
2 |
→ |
3 |
→ |
5 |
→ |
8 |
→ |
13 |
→ |
21 |
→ |
34 |
→ |
55 |
How can we turn such a picture above into code? Well, consider the arrow as part of the box to the left, that is the one that the arrow is starting from. So a box will contain two things, a piece of information (the numbers here) and an arrow. Arrow? Like a pointer? Right. The arrow can be implemented as a pointer to … To what? To an integer? No, not really. To a box that holds both an integer and another pointer.
What do the arrows/pointers let us do? Move from one box to the next. But what if we wanted to move back? We would need arrows going the other way, too.
0 |
↔ |
1 |
↔ |
1 |
↔ |
2 |
↔ |
3 |
↔ |
5 |
↔ |
8 |
↔ |
13 |
↔ |
21 |
↔ |
34 |
↔ |
55 |
How could we represent such a thing? Each box has to have two arrows/pointers, one pointing left and one pointing right. This is called a doubly-linked-list. It is easier to move around such a list, but it is a little more work to maintain the extra pointers.
So we need a “thing” that can hold a piece of data and a pointer (or two pointers if we want a doubly-linked-list). We commonly call such a thing a “node”. How can we implement a node? With a struct.
Nodes are very, very simple. All we do with them is create them, and possibly change their data or pointers. With such an extremely simple structure, we sometimes skip the overhead of coding with accessors and mutators. Instead, everything, even the member variables, is public. In fact there really isn’t anything else except a constructor (and perhaps a display function).
struct Node {
public:
int data;
Node* next;
};
So we can build linked lists with the Node struct. But we need to be able to do things with lists. For that we need to code up some typically useful functions. Implementations for several of these functions will be provided on the Sample Code portion of the course website.
Maintained by John Sterling (jsterling@poly.edu). Last updated January 23, 2011