I'm trying to create a linked list to store student's informations, with Student is a struct like this:
struct Student
{
int id;
string name;
//etc
}
I have two templates for node and list with a basic function:
template <class T>
struct Node {
T data;
Node <T> *pNext;
Node () : pNext(NULL) {}
Node (T &a) : data(a), pNext(NULL) {}
};
template <class T>
class LinkedList
{
Node <T> *Head;
size_t lSize;
public:
LinkedList(): Head(NULL), lSize(0) {}
~LinkedList();
void linsert(T& a);
};
With linsert() to insert new node at the beginning of the list:
template <class T>
void LinkedList<T>::linsert(T& a)
{
if (Head==nullptr)
Head=a;
else
{
a->pNext=Head;
Head=a;
}
lSize++;
}
To the testing: I've tried creating new nodes and linking them manually (without using the linked list) and everything seems to work fine:
Node <Student> *s1 = new Node <Student>;
s1->data.id=1;
s1->data.name="Anna";
Node <Student> *s2 = new Node <Student>;
s2->data.id=2;
s2->data.name="Bob";
Node <Student> *s3 = new Node <Student>;
s3->data.id=3;
s3->data.name="James";
Here's the problem: I tried creating a new linked list, and use the linsert() to add new students to the list with a simple for loop:
LinkedList <Node<Student>> *l=new LinkedList <Node<Student>>;
for (int=0; i<10; i++)
{
Node <Student> *s = new Node <Student>;
s->data.id=i;
s->data.name="Name";
l->linsert(s);
}
When compile, I get this error message points to the line
l->linsert(s);
error: no matching function for call to 'LinkedList<Node<Student> >::linsert(Node<Student>*&)'
note: candicate: void LinkedList<T>::linsert(T&) [With T=Node<Student>]
note: no known conversion from argument 1 from 'Node<Student>*' to 'Node<Student>&'
I always have problem using pointer and reference so after a good hour not figuring anything out I gave up. Please help me to solve this.
I'm using CodeBlock and if there's any improvement I can make for the above codes, it would be appreciated if you could tell me.
Aucun commentaire:
Enregistrer un commentaire