I'm implementing Doubly Linked List in C++, using templates. As I'm trying my hands on templates.
template <class T>
class DList{
Node<T> *head;
Node<T> *tail;
public:
Dlist(){
head = tail = nullptr;
}
void addToHead(T el){
Node<T> *newNode = new Node<T>(el);
if(head == nullptr){
head = tail = newNode;
}
else{
head -> prev = newNode;
newNode -> next = head;
head = newNode;
}
} };
When using this addToHead(), the if condition is not executing. And the program crashes.
They mistake was with the constructor function, it was just an typo. Because of which the head
and tail
pointers were not initializing and when the head
pointer was compared against the nullptr
in the if condition of the addToHead(), program was crashing.