In this advanced example, we have made the following enhancements:
Node class is now generic, allowing it to hold data of any type (T).SinglyLinkedList class is also generic, allowing it to create a linked list of any type.isEmpty and size methods provide information about the state and size of the linked list.insertFront method inserts a new node at the front of the list.insertEnd method inserts a new node at the end of the list.display method prints the elements of the linked list.In the main method, we create an instance of SinglyLinkedList called myList, and insert elements using the insertFront and insertEnd methods. We also display the size of the list using the size method and print the elements using the display method.
public class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
this.next = null;
}
public T getData() {
return data;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}
public class SinglyLinkedList<T> {
private Node<T> head;
private int size;
public SinglyLinkedList() {
this.head = null;
this.size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void insertFront(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
} else {
newNode.setNext(head);
head = newNode;
}
size++;
}
public void insertEnd(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
} else {
Node<T> current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(newNode);
}
size++;
}
public void display() {
Node<T> current = head;
while (current != null) {
System.out.print(current.getData() + " ");
current = current.getNext();
}
System.out.println();
}
public static void main(String[] args) {
SinglyLinkedList<Integer> myList = new SinglyLinkedList<>();
myList.insertFront(5);
myList.insertFront(10);
myList.insertEnd(15);
System.out.println("Size: " + myList.size());
myList.display();
}
}
When you run this code, it will output:
Size: 3
10 5 15
This demonstrates the advanced features of a generic singly linked list implementation in Java.