I'm really confused as to what exactly is going on here..
I have the function
void addToFront(int data)
{
Node* tmp = new Node();
tmp -> data = data;
tmp -> next = head;
head = tmp;
}
So when we do the line tmp-> next = head
, we are making the tmp
pointer point to what head
is pointing to (the current first element of the list)? Because that's what it feels like, but wouldn't that just make it point to head
? And then when we do head = tmp
, we are making head point to the new node that we created, correct?
This is how your list was (suppose)
Head
is pointing to locationA
.You make a new node
tmp
now points toB
. You insert data intmp->data
, and then maketmp -> next = head;
. So now we have:And then you make
head
to point toB
instead ofA
.head
&tmp
point toB
now.Correct.
No. To point to head, it would need to contain the address of head. But this line makes it contain the value of head. So no.
Yes.
If there is a head, the new node "next" will be point to the current head which is pointing to another node. and then head=x, the pointer called head is now set to point to the new node rather than the previous one