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:
class Node { int data; Node next; public Node(int d) { data = d; next = null; } }
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:
class SinglyLinkedList { Node head; public void add(int data) { // Create a new node with the given data Node new_node = new Node(data); // If the linked list is empty, then make the new node as head if (head == null) { head = new_node; } else { // Else traverse till the last node and insert the new_node there Node_last = list.head; while (last.next != null) { last = last.next; } // Insert the new_node at last node last.next = new_node; } } }
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.
@Override public String toString () { // For empty lists if (head == null) return "{}"; String str = "{" // Traverse the list until the last node Node current = head; while (current.next != null) { str += "" + current.data + ", "; current = current.next; } str += current.data + "}"; return str; }
Now, we can use our SinglyLinkedList class to store data:
public static void main(String[] args) { SinglyLinkedList list = new SinglyLinkedList(); list.add(1) list.add(27); list.add(-3); System.out.println(list); }
This code has the following output:
{1, 27, -3}
add() method code courtesy of GeeksForGeeks
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.