A typical linked list structure is made of three parts
The Data
class Bunny
{
string name; // don't use pointers unless you really, really need them
int age;
bool gender;
string color;
bool radioactive_bunny;
public:
string getGender(); // don't need to know which Bunny anymore because
// these functions are bound to a particular Bunny
string getName();
...
};
The Node
struct Node
{
Bunny data; // we will ignore templates for now. But they are rilly kool!
Node * next; // here is a good time to use a pointer: to point to the next node
Node(): next(nullptr) // node constructor. This really helps. Trust me.
{
}
}
Node
s know nothing except their data and a link to the next Node
. The dumber you can make a Node
, the safer you are. Also note that the Node
contains the Data. This allows you to easily swap out the Data without having to re-write the whole node and sets you up for easy templating of the Lined List structure later (though you’re probably better off jumping to std::list
).
And the Linked List:
class LinkedList
{
Node *head;
Node *tail;
Node *current; // not as useful as you might think
public:
LinkedList(): head(nullptr),tail(nullptr),current(nullptr)
{
}
void add(Bunny & bunny);
void remove(const string & bunnyname);
Bunny & get(const string & bunnyname);
Bunny & getNext(); // current may help here, but look into iterators
...
};
Note that we never let the caller at a Node
. They could do something stupid like delete
it or mangle Node::next
.
Adding, removing and iterating through the list has been beaten to death on Stack Overflow, so you should be able to find tonnes of examples of how to do this. For example: Using pointers to remove item from singly-linked list. There is, in my opinion, a really important trick in that link well worth the time spent learning. Pointers are like fire: A handy servant, but a terrifying master.
The big trick to getting linked lists is use a pencil and paper to draw the list and the nodes. See how they are connected. Redraw the list step by step as you add, remove, etc… so you can see how it needs to be done. Then write code to match the drawings. I know. Easier said than done, but way easier than banging your head against a wall with no plan whatsoever.
2
solved Advice on how to resolve this error.