In this example, we have two classes: Node represents a node in the linked list, and SinglyLinkedList represents the linked list itself. The Node class has two properties: data, which holds the value of the node, and next, which is a reference to the next node in the list.
The SinglyLinkedList class has a single property, head, which points to the first node in the list. It has methods to insert a new node at the end of the list (insert), and to display the elements of the list (display).
In the main method, we create an instance of SinglyLinkedList called myList, and insert three elements into the list using the insert method. Finally, we display the elements of the list using the display method.
When you run this code, it will output: 5 10 15, which are the elements of the linked list.
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class SinglyLinkedList {
private Node head;
public SinglyLinkedList() {
this.head = null;
}
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
SinglyLinkedList myList = new SinglyLinkedList();
myList.insert(5);
myList.insert(10);
myList.insert(15);
myList.display();
}
}