Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding node to the front of a linked list

Tags:

c++

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?

like image 921
FrostyStraw Avatar asked Dec 08 '22 12:12

FrostyStraw


2 Answers

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.

like image 112
Sadique Avatar answered Dec 11 '22 00:12

Sadique


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.

like image 38
David Schwartz Avatar answered Dec 11 '22 02:12

David Schwartz