3️⃣

16.3 Do It Yourself! - SinglyLinkedList

As you learned in a previous section, Singly Linked List is made of Nodes. Each Node contains a forward pointer to the next Node in the list, and it stores some data. For example, the first node in the list {“a”, “b”, “c”} has the character “a” as data, and it would store a pointer to the node with data “b.”

First, we need to construct a Node class:

image

This SinglyLinkedList will only be able to store integers as data. Notice that when a Node is initialized, the constructor will store the given data, and set the next node to NULL.

Next, we’ll construct the SinglyLinkedList class. Each list object only needs to store a pointer to the head node, since the head will point to Node 1, which will point to Node 2, and so on. The class also needs an add(int data) method, which will create a new Node with the given data.

The add method should add to the end of the list by changing the pointer in the current last node in the list from NULL to the new node. The new node will point to NULL, since it was initialized with next = null in the Node class above.

Here’s the final class:

image

Now you try

As an exercise, try adding an insert method that allows you to add data to a middle element, instead of only being able to add nodes to the end of the list.

Now, let’s add a toString() method to the SinglyLinkedList class, so that we can print out a list. The string will be in the “{data1, data2, data3, …}” format, which you should be familiar with from printing out ArrayLists.

image

Now, we can use our SinglyLinkedList class to store data:

image

This code has the following output:

image

add() method code courtesy of GeeksForGeeks

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.