Data Structures - Linked Lists

Hello there,

I have been studying data structures and there is a section on “Constructor and Adding to Head” under linked lists that I do not understand?

I am wondering why the step 4 ( Finally, still in your .addToHead() method, check if there is a current head to the list. If there is, set the list’s head’s next node to currentHead .) is needed.

Should the line “This.head = newHead” not be enough the make the newHead node the first node in the linked list ?

Please see the link below for further details

Yes, with this line you replace the old head with the new one making the new element the first in the list. But this new head isn’t yet linked to the rest of the list.
In this exercise you put a new node on top of the previous head, making the previous head the second element in the list. With step 4 you link the new head to the second element in the list which is the previous head. For that purpose you temporarily stored the previous head in the variable ‘currentHead’ in step 3.

Does that answer your question?

1 Like

Yes it does. Thank you very much.

1 Like

Thanks for your response again.

This time, I am trying to understand how to remove the head node.

I understand all the steps till step 3 but I do not understand why we have to return the removedHead’s data in step 4. I think we should be fine once we set this.head = removedHead.getNextNode().

By the way, I tried to implement the the removeHead method without the returning the removedHead’s data as in step 4 it it worked fine.

Please click the link for more info

I have done this exercise but not worked with linked lists in practice.
From what I see from the link you provided, you do not need to return the current, to be removed head’s data in order for the method to remove the current head and all nodes to be linked.
I suppose this will be crucial when working with linked lists: You might want to access the lists head in order to do something with it’s data. Once you proccessed the data, you would want to remove it from the list so you don’t use the same data again. I would imagine this to be equivalent to the .pop() or .unshift() methods for arrays. They remove the first/last item from the array while returning it at the same time.

1 Like

Thanks for your response.