hi everyone! Im hawa, one of your 123 TA’s and today we will be learning about linked nodes with loops! this topic is super fun but can get confusing at times, so we will need to ensure we understand the foundations of linked nodes, reference semantics, and we need to make sure to get lots of practice with this topic!

so quick review on what you all have learned in the last couple of weeks. so far, you guys have learned how to create this ListNode object that contains 2 fields, one being the data field that stores some integer, and the second field called next which acts a reference to the another ListNode. and this next field is really what links our nodes together. so how we constructed a new ListNode is by writing Listnode node = new Listnode() and passing in the data value we want to store in that node, and also either passing in a reference to the next node, or keeping the next field at null if we dont want to point it to anything!

so this linked node chain you see down here is just a series of these individual ListNodes which are linked together via the next pointers to create this list structure .

so real quick if we wanted to construct this linked node chain with the values [1,2,3,4], we would start by creating a front variable that references the first ListNode or element in our list. In this case, we will say, ListNode front = new ListNode(1);

now, if we want to create this chain of 2,3,4 we can just set the next fields.

so to link the number 2 to come after 1, we would just say front.next = new ListNode(). then if we want to add 3, we know that front.next references this ListNode which contains 2, so we add one more .next to reference after 2 and so we have

front.next.next = new ListNode(3).

lastly, we do the same with the value of 4, which you guys are familiar with by now, and we can say

front.next.next.next = new ListNode(4)

so notice that there is no next node that comes after 4, so 4’s next field is just null. It is important that you guys see a key observation here, which is that the last node in our list should always have a next field of null, indicating that there are no other nodes which come after it. so we know we are at the end of a list, when we are on some node whose next pointer is null!

suppose we wanted to print every element in order of the above linked node chain! so to have something like [1,2,3,4]. In this case we know that front references our very first node, so we can say

System.out.println(front.data);

and we know the way we set node 2 was by referencing front.next so we know that is how we can get access to the ListNode containing 2 so we can s=jsut print out