Home > OS >  How to fix this error in my c linked list code, "LL is not a template"?
How to fix this error in my c linked list code, "LL is not a template"?

Time:12-13

Here is the code I have created a basic linked list with some operations, but unable to use template type. Says LL is not an template.


template <typename T>                         //typename 
class node
{
public:
    T data;                                  //type T
    node *next;
};
class LL
{
    node *head = NULL;

public:
    void insert(auto val)
    {
        node *n = new node;
        n->data = val;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            return;
        }
        else
        {
            node *temp = head;                    //head not declared error though I declared it 
            while (temp->next != NULL)
            {
                temp = temp->next;
            }
            temp->next = n;
            return;
        }
    }
    void display()
    {
        node *temp = head;                        //head not declared error though I declared it 
        while (temp != NULL)
        {
            cout << temp->data << "->";
            temp = temp->next;
        }
        cout << "NULL" << endl;
        return;
    }
};
int main()
{
    LL<int> obj;                     //its correctly defined
    obj.insert(1);
    obj.insert(3);
    obj.display();
    return 0;
}

It also gives more errors as commented in the code above.(all related to template).

CodePudding user response:

Closer to what you want. node and LL need separate template declarations.

template <typename T>
class node
{
public:
    T data; 
    node *next;
};

template <typename T>
class LL
{
    node<T> *head = NULL;

public:
    void insert(const T& val)
    {
        node<T> *n = new node;
        n->data = val;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            return;
        }
        else
        {
            node<T> *temp = head;
            while (temp->next != NULL)
            {
                temp = temp->next;
            }
            temp->next = n;
            return;
        }
    }
    void display()
    {
        node<T> *temp = head;
        while (temp != NULL)
        {
            cout << temp->data << "->";
            temp = temp->next;
        }
        cout << "NULL" << endl;
        return;
    }
};
  • Related