Devos
Devos

Reputation: 15

Add end node to linked list

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.

Upvotes: 1

Views: 92

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320401

A common idiom that allows one to handle all cases uniformly (i.e. avoid special processing for the "very first node in the list" situation) works as follows

void AddNode(int val) 
{
  Node *n = new Node();
  n->data = val;
  // Assuming that `n->next` is already null

  Node **pnext = &A;
  for (; *pnext != NULL; pnext = &(*pnext)->next);

  *pnext = n;

  DisplayList();
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521053

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();
}

Upvotes: 4

Related Questions