samedi 25 novembre 2017

if not working whilst comparing a pointer for null in doubly linked list

I'm implementing Doubly Linked List in C++. Here is the class definition of Node, used for nodes in the doubly linked list.

 template<class T>
    class Node{
        public:
            T data;
            Node *next, *prev;
            Node(){
                next = prev = 0;
            }
            Node(T el, Node *n = 0, Node *p = 0){
                data = el;
                next = n;
                prev = p;
            }
    };

Here's the code for doubly linked list -

template <class T>
class DList{
    Node<T> *head;
    Node<T> *tail;
    public:
        Dlist(){
            head = tail = 0;
        }       
        void addToHead(T el){
            Node<T> *newNode = new Node<T>(el);
            if(head == 0){
                head = tail = newNode;
            }
            else{
                head -> prev = newNode;
                newNode -> next = head;
                head = newNode;
            }
        } };

When using this addToHead(), the comparison for if is not executing. And program crashes. Also, when the if is changed to

if(head == 0){

addToHead() is working fine, but every time it initializes the list even if there were elements present in it.

Aucun commentaire:

Enregistrer un commentaire