Singly linked list java: Implementation with code examples

Firstly, if you are working as a developer or programmer, Java is a must-have knowledge you should have to serve for your career. In fact, Java includes a tons of things. However, in order to work well with Java, one of the most essential things you have to concentrate on is Singly linked list java. So, what is this and how to implement it with ease? So, if you don’t have any knowledge about this topic, this article is for you.

Then, through this blog, ArrowHiTech will deliver you all useful information about it accompanied with code illustrated examples. So, what are you waiting for without exploring it right now!

What is Singly linked list java?

Firstly, you should know what does Singly linked list java mean. In fact, it is the most common type of Linked List. Besides, it has a data field and a single pointer to the next node in the list. Besides, the HEAD of the list is a reference to the first node in the list. The node’s pointer/reference/link field is used to go to the next node, and then to that node’s next node, and so on, until we reach a node that points to NULL. 

Then, this is the list’s final node. A single linked list can also only be navigated in one way, from the head to the last node. Also, there is no method to get back to the head from the previous node. 

Singly linked list java

Example of Singly linked list java

  • Firstly, a Linked List is a collection of things known as nodes that are kept in memory at random.
  • Secondly, a node has two fields: data saved at that specific address and a pointer to the next node in the memory.
  • The null pointer is contained in the list’s last node.
Singly linked list java

Now, let’s take a look at the following code program:

public class LinkedListExamples  

{  

 Node head;  // head of list  

 static class Node {  

 int data;  

         Node next;  

 Node(int d)  { data = d;  next=null; }  

     }  

     /* This function prints contents of the linked list starting from head */  

 public void display()  

     {  

         Node n = head;  

 while (n != null)  

         {  

 System.out.print(n.data+” \n”);  

             n = n.next;  

         }  

     }  

     /* method to create a simple linked list with 3 nodes*/  

 public static void main(String[] args)  

     {  

         /* Start with the empty list. */  

 LinkedListExamples list = new LinkedListExamples();  

 list.head       = new Node(100);  

         Node second      = new Node(200);  

         Node third       = new Node(300);  

 list.head.next = second; // Link first node with the second node  

 second.next = third; // Link first node with the second node  

 list.display();  

     }  

}  

Then, you will get the output like:

code output

How to create a Singly Linked List Java? 

Firstly, a self-referential class in Java can be used to build a singly linked list Java. In fact, a self-referential class is one that keeps track of its own existence. Then, you can refer to the program below that describes a class SinglyLinkedList that encloses an inner self-referential class Node that has two fields: an integer data field and a Node type “next” field. In addition, the outer class contains a reference/pointer/link to the HEAD of the document.

public class SinglyLinkedList {

    // reference to head / first node of the Singly Linked List

    public Node head = null;

    // class Node that hold data and a reference/link

    // to the next Node in the list

    class Node {

        private int data;

        private Node next;

        public Node(int data) {

            this.data = data;

            this.next = null;

        }

    }

}

Way to insert Nodes Into a Singly Linked List 

Firstly, in the previous part, we showed you the best method to generate a Singly Linked list Java. Then, in this part of our article, we will indicate the way to insert Nodes into a Singly linked list. In order to insert Nodes into a Singly Linked List, it consists of three curriculums like below:

#1. Firstly, Beginning of the list

#2. Secondly, End of the list

#3. Thirdly, Specified position in the list.

So, coming to each scenery to know how to insert Nodes into a Singly Linked List in the most effective way.

#1. Beginning of the list

Firstly, moving to the first case to insert Nodes into a Singly Linked List. The following algorithm is used to add a new node to the beginning of the list:

  • Firstly, assign the HEAD’s reference to the next field of the new node.
  • Secondly, set the new node as the list’s HEAD.
Singly linked list java

Then, you should apply code below to completely add a new node to the beginning of the list. So, let’s see:

// Point the new node’s next to head

newNode.next = this.head;

// Make the new node as head

this.head = newNode;

#2. End of the list

Firstly, let’s come to the way to add a node to the end of the list. The following algorithm is used to do that: 

  • Continue down the list until we reach the last node.
  • Secondly, the next field of the previous node is allocated to the new node’s reference.
end of the list

Then, if you want to insert a node to the end of the list, let’s follow the code program like below:

Node cur = this.head;

// traverse to the end of the list

while (cur.next != null) {

    cur = cur.next;

}

cur.next = newNode;

#3. Specified position in the list

The following algorithm is used to insert a node at a specific place in the list —. So, let’s refer to them!

  • Firstly, Maintain previous and current references when traversing (position – 1) times or until the end of the list is reached.
  • Secondly, assign the new node’s reference to the previous node’s next field.
  • Thirdly, assign the current node’s reference to the next field of the new node.
Specified position in the list

Then, let’s examine the following program in order to know how to insert a node at a specific place in the list:

// traverse to the end of the list and check positions moved

while (cur.next != null && –position > 0) {

    // update the prev and cur references

    prev = cur;

    cur = cur.next;

}

// update prev to point to new node

prev.next = newNode;

// & new node to point to current node

newNode.next = cur;

Firstly, do you want to see about all three operations above? If “YES”, let’s move to the following program. In particular, the code below demonstrates how to generate a Singly linked list java. So, let’s start now!

public class Main {

// reference to head / first node of the Singly Linked List

public Node head = null;

// class Node that hold data and a reference/link

// to the next Node in the list

class Node {

private int data;

private Node next;

public Node(int data) {

this.data = data;

this.next = null;

}

}

    /*

* Method to add a node at the beginning of the list

*/

public void addNodeAtTheBeginning(int data) {

        System.out.println(“Add a node with data ” + data + ” in the beginning.”);

// Create a new node

Node newNode = new Node(data);

// Check if the list is empty

if (this.head == null) {

// Make the new node as head

this.head = newNode;

} else {

// Point the new node’s next to head

newNode.next = this.head;

// Make the new node as head

this.head = newNode;

}

}

    /*

* Method to add a node at the end of the list

*/

public void addNodeAtTheEnd(int data) {

        System.out.println(“Add a node with data ” + data + ” at the end.”);

// Create a new node

Node newNode = new Node(data);

// Check if the list is empty

if (this.head == null) {

// Make the new node as head

this.head = newNode;

} else {

Node cur = this.head;

// traverse to the end of the list

while (cur.next != null) {

cur = cur.next;

}

cur.next = newNode;

}

}

/*

* Method to add a node at the specified position in the list

*/

public void add(int position, int data) {

        System.out.println(“Add a node with data ” + data + ” at the position ” + position);

// Create a new node

Node newNode = new Node(data);

// Init the cur and prev nodes to the head

Node cur = this.head, prev = this.head;

if (position == 1) {

// Point the new node’s next to head

newNode.next = head;

// Make the new node as head

this.head = newNode;

return;

}

// traverse to the end of the list and check positions moved

while (cur.next != null && –position > 0) {

// update the prev and cur references

prev = cur;

cur = cur.next;

}

// update prev to point to new node

prev.next = newNode;

// & new node to point to current node

newNode.next = cur;

}

   public void print() {

if (this.head == null) {

System.out.println(“The List is empty.”);

} else {

System.out.println(“The contents of the Singly Linked List are : “);

Node cur = this.head;

while (cur != null) {

System.out.print(cur.data + ” -> “);

cur = cur.next;

}

System.out.println(“NULL\n”);

}

}

   public static void main(String[] args) {

        Main list = new Main();

        System.out.println(“Created a singly linked list …..”);

    list.print();

list.addNodeAtTheBeginning(100);

    list.print();

list.addNodeAtTheBeginning(200);

list.print();

       list.addNodeAtTheEnd(900);

    list.print();

list.addNodeAtTheEnd(800);

list.print();

        list.add(1,150);

        list.print();

        list.add(4,250);

        list.print();

        list.add(6,250);

        list.print();

    }

}

How to delete Node from a Singly linked list Java?

In fact, deleting Node from a Singly linked list java is quite sophisticated with a lot of people. This is because the node to be deleted could be the first, last, or in the middle of the list. Now, let’s take a look at each scenario individually to understand in detail:

#1. First Node

Firstly, below is the instruction for you to delete First node. So, let’s explore it now!

// If the data is found at the first node

if (this.head.data == data) {

    this.head = this.head.next;

    return;

}

#2. Last Node or Any Other Node

First of all, we traverse the list, follow the previous and current nodes in the list, until we discover the node to be deleted with the requisite data field, or we reach the list’s end, i.e. NULL, without finding the data element in the list in order to delete any other node in the list. 

What’s more, we assign the reference of the current node’s next field to the previous node’s next if the node is found.

So, the image below will show you the information about deleting any node from a Singly linked list java:

Singly linked list java

Then, the codes will let you know the way to delete any node

// Traverse the list until it ends or you

// find the node that holds the data

while (cur != null && cur.data != data) {

    // update the prev and cur references

    prev = cur;

    cur = cur.next;

}

// If the node was found, adjust the prev node

// to point to the next of the node to be deleted.

if (cur != null) {

    prev.next = cur.next;

} else {

    System.out.println(“The data ” + data + ” could not be found in the List”);

}

Then, the code below shows how to delete items from a Singly Linked List. So, in order to see the code in action, let’s press the play button.

public class Main {

public Node head = null;

// class Node that hold data and a reference/link

// to the next Node in the list

class Node {

private int data;

private Node next;

public Node(int data) {

this.data = data;

this.next = null;

}

}

/*

* Method to add a node at the end of the list

*/

public void addNodeAtTheEnd(int data) {

// Create a new node

Node newNode = new Node(data);

// Check if the list is empty

if (this.head == null) {

// Make the new node as head

this.head = newNode;

} else {

Node cur = this.head;

// traverse to the end of the list

while (cur.next != null) {

cur = cur.next;

}

cur.next = newNode;

}

}

/*

* Method to delete the first occurrence of data in the list

*/

public void deleteFirstOccurenceOfData(int data) {

        System.out.println(“Deleting First Occurance of data ” + data + ” from the list”);

// Check if the list is empty

if (this.head == null) {

System.out.println(“The List is empty.\n”);

return;

}

// Init the cur and prev nodes to the head

Node cur = this.head, prev = this.head;

// If the data is found at the first node

        // assign the reference of current head’s next to head

if (this.head.data == data) {

this.head = this.head.next;

return;

}

// Traverse the list until it ends or you

// find the node that holds the data

while (cur != null && cur.data != data) {

// update the prev and cur references

prev = cur;

cur = cur.next;

}

// If the node was found, adjust the prev reference

// to point to the next of the node to be deleted.

if (cur != null) {

prev.next = cur.next;

} else {

System.out.println(“The data ” + data + ” could not be found in the List”);

}

}

/*

* Method to display the nodes of the singly linked list

*/

public void print() {

if (this.head == null) {

System.out.println(“The List is empty.”);

} else {

System.out.println(“The contents of the Singly Linked List are : “);

Node cur = this.head;

while (cur != null) {

System.out.print(cur.data + ” -> “);

cur = cur.next;

}

System.out.println(“NULL\n”);

}

}

public static void main(String[] args) {

Main list = new Main();

       for (int i=1;i<=8;i++) {

list.addNodeAtTheEnd(i);

}

list.print();

list.deleteFirstOccurenceOfData(1);

list.print();

list.deleteFirstOccurenceOfData(8);

list.print();

list.deleteFirstOccurenceOfData(4);

list.print();

}

}

Does Singly linked list java have any disadvantages?

In reality, Singly linked list Java also includes some drawbacks. But, which are they? Then, let’s check them below:

  • Firstly, individual elements cannot be accessed directly. Besides, the only method to get to the required node is to start at the HEAD and follow the references in each node.
  • Secondly, when storing the reference to the next node, a single linked list consumes more memory than an array.

In conclusion

In short, this blog is an overview of Singly linked list java about its definition, its implementation and even its drawbackes. Besides, through this blog, ArrowHiTech dug down a lot of useful information about Singly linked list java for you. Besides, we also brought several specifical code examples for you to implement Java with ease. Then, ArrowHiTech hopes these things we provide will be beneficial for you and you can adapt them into practical. However, if you have any inquiry or problems, let’s CONTACT US. Then, we will surely help you solve it instantly. 

Tags

Share