Answer the question
In order to leave comments, you need to log in
How does the head of the list change on insertion?
Stupid newbie question:
There is a piece of C++ code that describes inserting a new element at the head of a list:
void LinkedList::headInsert(int val)
{
/* The list is empty? */
if (_pHead == NULL) {
/* the same to create a new list with a given value */
_pTail = _pHead = new Node(val);
}
else
{
/* Create a new node and insert it before the head node */
Node *node = new Node(val);
node->_pNext = _pHead;
/* Update the head node */
_pHead = node;
}
}
/* Update the head node */
_pHead = node;
Answer the question
In order to leave comments, you need to log in
I'll try to tell you somehow :) The first point - I hope it's clear that if there is no head, then it is created, and if there is, then an element is added. The code specifies a Node class. When creating an object from this class, we take the value val as the value of this object. Also in this object there is a link to the next object, which is necessary for the implementation of the list.
Let's say there is 1 element in the list. Each element is an object of class Node. It has a certain value, and a link to the sld. an object. But since there is no object, the reference points to NULL.
Insert a new element. To do this, we create a new object of the Node class with the required value. Link that will enter the next. the object we point to the head of this list. Now we have 2 different objects (with *node = new Node(val) different class objects are created). And for the finish, we indicate that the head is our new element / object
up to this line node points to the head
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question