If we are going to put an object, say student, car, complex, or stock in a linked list, we need to have a "next" pointer in the node. In other words, a node has an object and needs a pointer to the next node. There are a few ways to implement the node. Let's use student object as an example.
1. copy student class and add one more field student *
class studentNode {
string first_name;
string last_name;
unsigned id;
int grade;
studentNode *next;
}
This copy method happens often, but it is highly discouraged. Why? Everything in student class will be duplicated. Totally defeat the purpose of code reuse. Don't do this!! It is against Frank's 3R.... reduce, reuse, and recycle.
2. define studentNode as a struct
struct studentNode {
student s;
studentNode *next;
}
3. define studentNode as has-a class
class studentNode {
student s;
studentNode *next;
}
The struct method and has-a method are very similar. Struct is a carry over from C data type. The has-a approach has a better control of the class (e.g. constructor, operator overloading.)
There is one major difference between struct and has-a though: The class members are default to "private". In most cases, you need to adjust some of them to be public.
4. define studentNode as is-a class
class studentNode : public student {
studentNode *next;
}
The is-a method leverages the inheritance capability in C++. It is arguably cleaner and clearer. It is my preferred approach. Try both has-a and is-a approaches and validate your own preference.
Discussions:
So, what if I want to create node for a doubly-linked list? Yes, I can reuse studentNode above, but I would not recommend it. Instead, I will create a new node studentNodeD such as:
class studentNodeD {
student s;
studentNodeD *prev;
studentNodeD *next;
}
class studentNodeD : public student {
studentNodeD *prev;
studentNodeD *next;
}