In this example, we have the same Node and SinglyLinkedList classes as before. The Node class represents a node in the linked list, and the SinglyLinkedList class represents the linked list itself.
In the insert method, instead of traversing the list to find the last node and appending the new node at the end, we prepend the new node at the beginning of the list. This way, the newly inserted node becomes the new head of the list.
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. However, note that the order of the elements is reversed compared to the previous example, as the new nodes are inserted at the beginning of the 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 {
newNode.next = head;
head = 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(15);
myList.insert(10);
myList.insert(5);
myList.display();
}
}