Java Program to Create and Display a Singly Linked List

Java program to create and display a singly linked list. A Linked List is a collection of objects known as nodes that are stored in memory at random. A node has two fields: data stored 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. The list’s first node is known as the head, and the list’s last node is known as the tail. A pointer to the null is contained in the list’s last node. By traversing the list from head to tail, each node in the list can be accessed in a linear fashion.

public class Main
{

class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public Node head = null;
public Node tail = null;
public void addNode(int data)
{
Node newNode = new Node(data);

if(head == null) {

head = newNode;
tail = newNode;
}
else {

tail.next = newNode;
tail = newNode;
}
}
public void display()
{
Node current = head;
if(head == null)
{
System.out.println("List is empty");
return;
}
System.out.println("The elements of the singly linked list is");
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args)
{
Main sList = new Main();
sList.addNode(10);
sList.addNode(20);
sList.addNode(30);
sList.addNode(40);
sList.display();
}
}

 

Output:

10

20

30

40

Singly Linked List in Java

A singly linked list is a sort of unidirectional linked list that may only be traversed in one direction, from head to final node. A node is the name for each element in a linked list. A single node contains data as well as a pointer to the next node, which aids in the list’s structure. It is used to implement stacks and queues, which are basic computer science requirements. We utilize a singly linked list to avoid data in the hash map from colliding.

Advantages of Singly Linked List in Java

In the forward path, a node’s accessibility is much easier. A node’s insertion and deletion are both simple. When compared to a double, circular, or doubly circular linked list, the Requirement will use less memory.

Node in Java

In Java, an Individual Node is a class used to build individual data holding blocks for various data structures that organise data in a nonsequential manner. Each node in a linked list is an object of the node class; each node is often depicted as a box containing one or more pieces of data. Each node provides information as well as a link to another node. A piece of data is saved in the node’s instance variable. In this program we can execute java program to create and display a singly linked list.