Write a java program to create a singly linked list and display the element

Write a java program to create a singly linked list and display the element. 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