Creating a linked list is easiest if you have two separate classes, a Node/Item and a List class. The List class simply keeps track of the head of the list (and other metrics if you wish, like item count etc). The Node class does the actual linking by means of a Next and Prev pointer, and keeps the data of the item itself. This can easily be done as such:
1 2 3 4 5 6 7
|
struct Node {
myItem* Data; // Points to whatever class you wanted a LL of.
Node* next, *prev; // Links
};
struct List {
Node* head;
};
|
Second problem: data management. In most cases, a linked list is used for "an unknown amount of items", thus you can't initialize a fixed size container for it. Generally, new items are added on the Heap using dynamic allocation.
1 2
|
List mylist;
mylist.push(new Node(InitData));
|
This is handy, because memory is only allocated when a new item appears. More difficult, however, is keeping track of it. After all, the only way to find the items is by the pointers in the next/prev pointers of other nodes. If you decide to delete an item from the list by relinking its neighbors, you best make sure you keep a pointer to the deleted item, or you'll have lost it forever (= memory leak!).
Secondly, once you're done, you need to delete
all the items. Sadly, you don't have a pointer to
all the items, and once you delete a single item, you lose the links to the other items, and those links are the only way to find the items!
Often, this is done by a recursive deletion algorithm that is called in the destructor:
1 2 3 4 5 6 7 8
|
void List::empty(void) {
head->prev->next = nullptr; // Break forward-circularity.
head->delete(); // Call recursive deleter.
}
void Node::delete(void) {
if(next != nullptr) next->delete(); // Recursively destroy the next item;
delete this; // Clear memory of this Node.
}
|
The recursion first deletes the next item, then itself. This means the last item will be deleted first (it is the only item where next = nullptr, because we enforced it!), before the recursion walks back.
Do mind, this is untested; I'm simply trying to explain the basics. I'm not sure if you can call delete on 'this'. Most likely, you're going to call "delete next;" and a final "delete head;" instead.