如何在我的c ++链表代码中修复此错误,"LL is not a template"?



这是我创建了一个基本的链表与一些操作,但无法使用模板类型的代码。说明LL不是模板。


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;
}

还会像上面代码中注释的那样给出更多错误。(均与模板相关).

更接近你想要的。node和LL需要单独的模板声明。

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;
}
};

相关内容

  • 没有找到相关文章

最新更新