C++ Linked List Insert Implementation

Disclaimer: I am somewhat new to coding, and this is a pretty simple question, but I can’t quite find the answer anywhere else, so I decided to ask my first question here, I hope it hasn’t been asked already(if it has, I haven’t found it). I hope this is an appropriate forum for my question.

I’m trying to create a linked list for a course I’m taking. I’m struggling with inserting a new value at the end of the list. Here is my add/insert method, which I basically stole from my textbook, but I’m confused about:

class Node {

public:

    int elem = 0;

    Node* next = NULL;
}; // I'm including the Node class in this question for reference


//Here's the method that confuses me  
void SList::Insert(int key) {                      // add to front of list

  Node* v = new Node;                                // create new node

  v−>elem = e;                                       // store data

  v−>next = head;                                    // head now follows v

  head = v;                                          // v is now the head
}

I guess my question is this: when the add method runs, it creates a new node, v, whenever it is called (at least, that’s how I understand it). If the method is called multiple times, doesn’t this create multiple instances of the node class with the same name (v), which should cause an error?

The code does work as intended, but I’m hoping somebody can take a second to explain to me why it works. I’m not super familiar with C++, I’m much more familiar with java, so I’m guessing there’s just some aspect of C++ I don’t understand.

Answer

First things first, this code snippet is inserting a new node at the beginning of our linked list (which is identified by the head pointer) and not at the end. v is a temporary identifier to hold our new node which is not attached to our list yet. Let’s say our list looks like this initially:

[head] -> [1,n2] -> [2,n3] -> [4,NULL].

(head is only a node pointer, not a node)

After this statement v−>elem = e; we have our new node as : [v] -> [e,NULL]

v−>next = head; : this line doesn’t mean head follows v, it just means we are setting our new node to point to the same node where head is pointing to. So now our list will look like this:

[v] -> [e,n2] -> [1,n2] -> [2,n3] -> [4,NULL]

Note: [head] is still pointing to our second node [1,n2], which should now be pointing towards our first newly created node, which is achieved by our last line head = v;. v now goes out of scope and our list looks like this :

[head] -> [e,n2] -> [1,n2] -> [2,n3] -> [4,NULL]