Devos - 8 months ago 60

C++ Question

Can't seem to pin down what I'm missing here. I know how to properly insert a new node at the beginning of my linked list:

`void InsertBeginning(int val) {`

Node *n = new Node();

n->data = val;

n->next = A;

A = n;

DisplayList(); //prints list

}

And now I wish to do the same thing but at the end of my list, so then I made this:

`void AddNode(int val) {`

Node *n = new Node();

n->data = val;

n->next = A;

//finds last empty node

while (n->next != NULL) {

n = n->next;

}

A = n;

DisplayList();

}

But all this does is delete everything but my first node.

Answer

Walk down the list and then add the new node. Note that there is no need to modify `A`

, which presumably points to the head of the list, because it doesn't change.

```
void AddNode(int val) {
Node *n = new Node();
n->data = val;
n->next = NULL;
Node *pnt = A;
// If list is empty, new node becomes first node
if (!pnt) {
A = n;
return;
}
//finds last empty node
while (pnt->next != NULL) {
pnt = pnt->next;
}
pnt->next = n;
DisplayList();
}
```

Source (Stackoverflow)