// Node class representing each element of the list
class Node {
int data;
Node next;
Node(int
data) {
this.data = data;
this.next = null;
}
}
// LinkedList class with basic operations
public class MyLinkedList {
private Node head;
// Add element to
end of the list
public void add(int data) {
Node newNode = new Node(data);
if (head ==
null) {
head = newNode;
return;
}
Node current =
head;
while (current.next !=
null) {
current = current.next;
}
current.next = newNode;
}
// Remove element
by value
public void remove(int data) {
if (head ==
null) return;
if (head.data == data) {
head = head.next;
return;
}
Node current =
head;
while (current.next !=
null) {
if (current.next.data == data) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
// Print the
linked list
public void printList()
{
Node current =
head;
while (current != null) {
System.out.print(current.data +
" -> ");
current = current.next;
}
System.out.println("null");
}
// Return size of
the list
public int size() {
int count = 0;
Node current =
head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
// Check if list
is empty
public boolean isEmpty() {
return head ==
null;
}
// Main method to
test
public static void
main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.add(10);
list.add(20);
list.add(30);
list.printList(); // 10 -> 20
-> 30 -> null
list.remove(20);
list.printList(); // 10 -> 30
-> null
System.out.println("Size: " + list.size()); // Size: 2
System.out.println("Is Empty: " + list.isEmpty()); // false
}
}