class Node
{
int data; // Data part
Node next; // Pointer to the next node
// Constructor
Node(int data)
{
[Link] = data;
[Link] = null;
}
}
class LinkedList {
private Node head; // Head of the linked list
// Add a new node to the end of the list
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
}
else
{
Node current = head;
while ([Link] != null)
{
current = [Link];
}
[Link] = newNode;
}
}
public boolean remove(int data)
{
if (head == null)
{
return false; // List is empty
}
if ([Link] == data)
{
head = [Link];
return true;
}
Node current = head;
while ([Link] != null && [Link] != data)
{
current = [Link];
}
if ([Link] == null)
{
return false; // Data not found
}
[Link] = [Link];
return true;
}
public void display()
{
if (head == null)
{
[Link]("List is empty.");
return;
}
Node current = head;
while (current != null)
{
[Link]([Link] + " -> ");
current = [Link];
}
[Link]("null");
}
public boolean search(int data)
{
Node current = head;
while (current != null)
{
if ([Link] == data)
{
return true;
}
current = [Link];
}
return false;
}
}
public class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList list = new LinkedList(); // Adding elements to the list [Link](10);
[Link](20);
[Link](30);
[Link]("Linked List after additions: ");
[Link](); // Removing an element
[Link](20);
[Link]("Linked List after removing 20: ");
[Link]();
boolean found = [Link](30);
[Link]("Is 30 in the list? " + found);
boolean remove = [Link](40);
[Link]("Trying to remove 40: " + (remove ? "Remove" : "Not Found"));
[Link]("Final Linked List: ");
[Link]();
}
}