The Single Linked List Program in Java creates a node, inserts a node, and prints the linked list.
class Node
{
int data;
Node next;
//initialize a node
public Node(int data)
{
this.data = data;
this.next = null;
}
}
class LinkedDemo
{
//first or head node of the list
Node head;
public void insert(int data)
{
Node newNode = new Node(data);
// If the list is empty, create the head
if (head == null)
{
head = newNode;
}
else
{
Node current = head;
//find end of the list
while (current.next != null)
{
current = current.next;
}
//insert the new node at the end
current.next = newNode;
}
}
//Method to display the linked list
public void display()
{
if (head == null)
{
System.out.println("The list is empty.");
return;
}
Node current = head;
while (current != null)
{
System.out.print(current.data + " -> ");
current = current.next;
}
}
public static void main(String[] args)
{
LinkedDemo list = new LinkedDemo();
// Insert nodes into the list
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
// Display the list
System.out.println("Linked List:");
list.display();
}
}