I am trying to write a code for a linked list but when I try to add a node the code gets stuck at the line immediately after the while loop in the add() function, reporting an access violation error. What’s wrong?
#include<iostream>
template <class T>
class linkedlist
{
struct node
{
T data;
node *lp;
}*p;
public:
linkedlist();
void add(T t);
};
template<class T>
void linkedlist<T>::add(T t)
{
node *r,*q;
r = q = p;
while(p!= NULL)
{
q = p;
p = p->lp;
}
q->lp = new node;
q->lp->data = t;
p = r;
}
template<class T>
linkedlist<T>::linkedlist()
{
p = NULL;
}
int main()
{
linkedlist<int> l1;
l1.add(3);
}
You initialize
ptoNULLin the constructor, then try to dereference it inadd(viaq):You must initialize
pfirst – either during construction (in which case your “empty” list won’t be physically empty, so you must deal with this specifically, e.g. when iterating / removing elements), or you should check inaddfor the case whenp == nulland handle it differently.Side note:
pis supposed to point to your head element, so it is risky to use it also to iterate through the list inadd, then restore its original value (stored inr). Why not simply leave it always intact, and userfor iterating? One less chance for bugs.