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)
+----+-----+ +-----+-----+ +-----+------+
| A | +-->| | +-->| | |
+----+-----+ +-----+-----+ +-----+------+
/
Head
is pointing to location A
.
You make a new node
+----+----+
| B | |
+----+----+
/
tmp
now points to B
. You insert data in tmp->data
, and then make tmp -> next = head;
. So now we have:
+----+----+ +----+-----+ +-----+-----+ +-----+------+
| B |next|---->| A | +-->| | +-->| | |
+----+----+ +----+-----+ +-----+-----+ +-----+------+
/
And then you makehead
to point to B
instead of A
.
+----+----+ +----+-----+ +-----+-----+ +-----+------+
| B |next|---->| A | +-->| | +-->| | |
+----+----+ +----+-----+ +-----+-----+ +-----+------+
/ \
head
& tmp
point to B
now.
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,
Correct.
but wouldn't that just make it point to head?
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.
And then when we do head = tmp, we are making head point to the new node that we created, correct?
Yes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With