First, in linkedList::addNode
method, you have the construction if (head = NULL)
, which will wind up assigning to head
; you want the ==
operator.
Second, about the line:
head = &(Node (value, NULL));
For somewhat unintuitive reasons, this won't work. You'll get a reference to a Node
, but that node will go out of scope as soon as the method ends, and attempts to reference it will lead to a segmentation fault. You need to use the new
operator (same with the other similar line):
head = new Node(value, NULL);
If you add a method for removing a node, make sure to delete
the node then—it won't get automatically garbage-collected like it will in Java.
Sidebar: Think of what happens like this: when you do Node(value, NULL)
, you're using a temporary variable that's declared like this:
Node hiddenTempNode(value, NULL);
This doesn't allocate space for an object anywhere except on the stack—it's very similar to allocating space for an int
and a Node *
on the stack as separate variables. As a result, as soon as you leave the method, the object disappears and the pointer to it will do weird things when used.
Third, beware: you may want to set next = NULL
in your single-parameter constructor, to ensure that it always has a value. Similarly for your default constructor.
Fourth: your linkedList::print
method is looping until p->next
is NULL
and printing the value of p->next
; those occurrences of p->next
should probably be changed to just p
if you want to get the first and last items.