Look at this apparently harmless line (found in addNode
):
head->next->next = NULL;
This line is breaking your linked list. By the time you add three elements, this line will cut the list. That is, your list will look like this:
head tail
node -> node -> null node -> null
When you expect it to look like this:
head tail
node -> node -> node -> null
And of course, if you iterate from head
to tail
without checking pointers you end up finding that third node that is null
and that's where the problems start.
Since you are in C ++ I suggest, as you do in the other answer, that you stop using malloc
and you happen to use new
. Along with this change, define an appropriate constructor and the problem will be solved only :
struct nodeDouble{
int data;
nodeDouble* next;
nodeDouble* prev;
nodeDouble(int value)
: data(value),
next(nullptr),
prev(nullptr)
{ }
};
nodeDouble* head = nullptr;
nodeDouble* tail = nullptr;
void addNode(int number){
nodeDouble * node = new nodeDouble(number);
if(head == nullptr){
head = node;
}else{
tail->next = node;
node->prev = tail;
}
tail = node;
}
What happens now is that new
invokes, implicitly, the constructor that we declared in the class. This constructor initializes the pointers next
and prev
a nullptr
(natural substitute of NULL
in the C ++ 11 standard). In addition also initializes data
from a value that we provide.
Later we will only update those pointers that we need and that's it, the list will be correctly linked.
We could also create a little more complete builder:
struct nodeDouble{
int data;
nodeDouble* next;
nodeDouble* prev;
nodeDouble(int value, nodeDouble* previous)
: data(value),
next(nullptr),
prev(previous)
{
if( nullptr != previous )
previous->next = this;
}
};
nodeDouble* head = nullptr;
nodeDouble* tail = nullptr;
void addNode(int number){
nodeDouble * node = new nodeDouble(number,tail);
if(head == nullptr)
head = node;
tail = node;
}
Now the constructor also receives a pointer to the previous node. If this pointer is null, it does nothing, but if it is not, it adds to the end of the list, so it would only be necessary to update tail
.