Your latest code compiles and runs for me.
For efficienct, AddNode should add the node to the front of the list. Otherwise creating a large list will take forever because each time you add a new element, the code must traverse the WHOLE list:
1 2 3 4 5 6 7
|
void AddNode(int addData)
{
nodePtr n = new node;
n->data = addData;
n->next = head;
head = n;
}
|
Why are temp and curr members of the list class? There's no need to store them in between calls to the methods so they should be local variables.
You can greatly simplify DeleteNode. The trick is to keep a pointer to the pointer to the current node rather than a pointer to the current node or nullptr. The pointer-to-pointer will point to
head
, or the
next
pointer of the previous node:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
void DeleteNode(int delData)
{
for (nodePtr *headOrNext = &head;
curr = *headOrNext;
headOrNext = &curr->next) {
if (curr->data == delData) {
*headOrNext = curr->next;
delete curr;
cout << "The Value " << delData << " was deleted.\n";
return;
}
}
cout << delData << " was not in the list\n";
}
|
Line 3 creates headOrNext, which is the pointer to pointer. It stars life pointing to head.
Line 4,
curr = *headOrNext
, is the test condition for the for loop. Notice that this is an assignment (
=
) rather than a comparison (
==
). It assigns curr to point to the current node. If the result is nullptr, the condition fails and the loop exits.
Line 5,
headOrNext = &curr->next
, sets headOrNext to point to curr's next pointer, thus setting up for another loop.
Line 8 is where headOrNext pays off. To unlink the current node, you simply say
*headOrNext = curr->next
. Since headOrNext points to whatever is pointing at curr, whether it's head or the previous node's next pointer, this line changes the pointer to point to the next item in the list (or nullptr is curr is the last node).