G
G
Gina Lee2015-10-26 01:51:45
Programming
Gina Lee, 2015-10-26 01:51:45

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

It's not clear what happens at the end
/* Update the head node */
        _pHead = node;

up to this line, the node points to the head, and the head of the list is assumed to be the original head of the list. And then how? We access the original head of the list and assign node to it. It turns out that a node is followed by a node (two identical elements). What am I misunderstanding?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Shaforostov, 2015-10-26
@Din7

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

A
abcd0x00, 2015-10-26
@abcd0x00

up to this line node points to the head

It does not point to the head, but to the fragment of memory just allocated via new.
But already inside this fragment of memory there is a pointer that points to the head.
Then they (the new node and the head) become connected and we can make the new node the head.
The old head is accessed through the new head.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question