class SinglyLinkedList {
// Node class to represent each node in the linked list
class Node {
int data;
Node next;
// Constructor to create a new node
public Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head; // head of the list
// Constructor to initialize an empty linked list
public SinglyLinkedList() {
head = null;
}
// Insert a node at the end of the linked list
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
// Traverse to the last node
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode; // Insert new node at the end
}
// Delete a node by key
public void delete(int key) {
Node temp = head;
Node prev = null;
// If the node to be deleted is the head node
if (temp != null && temp.data == key) {
head = temp.next; // Move head to the next node
temp = null;
return;
}
// Search for the node to be deleted
while (temp != null && temp.data != key) {
prev = temp;
temp = temp.next;
}
// If the key was not found
if (temp == null) {
System.
out.
println("Node with data " + key
+ " not found."); return;
}
// Unlink the node from the linked list
prev.next = temp.next;
temp = null;
}
// Search for a node with a specific value
public boolean search(int key) {
Node temp = head;
while (temp != null) {
if (temp.data == key) {
return true;
}
temp = temp.next;
}
return false;
}
// Display the linked list
public void display() {
if (head == null) {
System.
out.
println("List is empty."); return;
}
Node temp = head;
while (temp != null) {
System.
out.
print(temp.
data + " -> "); temp = temp.next;
}
}
// Main method to test the operations
public static void main
(String[] args
) { SinglyLinkedList list = new SinglyLinkedList();
// Insert elements into the list
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
System.
out.
println("Linked List after insertions:"); list.display();
// Searching for an element
int keyToSearch = 20;
if (list.search(keyToSearch)) {
System.
out.
println("Node with data " + keyToSearch
+ " found!"); } else {
System.
out.
println("Node with data " + keyToSearch
+ " not found."); }
// Deleting an element
int keyToDelete = 20;
list.delete(keyToDelete);
System.
out.
println("Linked List after deleting " + keyToDelete
+ ":"); list.display();
// Trying to delete a non-existing element
list.delete(50);
// Searching for a non-existing element
if (list.search(50)) {
System.
out.
println("Node with data 50 found!"); } else {
System.
out.
println("Node with data 50 not found."); }
}
}