public class SinglyLinkedList {
// Node class
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Head of the linked list
Node head;
// Method to add a node to the end of the list
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// Method to search for an element in the list
public boolean search(int data) {
Node current = head;
while (current != null) {
if (current.data == data) {
return true;
}
current = current.next;
}
return false;
}
// Method to display the list
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(4);
System.out.println("The list:");
list.display();
int searchValue = 3;
if (list.search(searchValue)) {
System.out.println("\nThe element " + searchValue + " is present in the list");
} else {
System.out.println("\nThe element " + searchValue + " is not present in the list");
}
}
}
The list:
1 2 3 4
The element 3 is present in the list
Node
class to represent a node in the linked list. Each node contains an integer data
and a reference to the next node in the list. The SinglyLinkedList
class contains a reference to the head of the list, a method to add a node to the end of the list, a method to search for an element in the list, and a method to display the list.addLast
method, a new node is created with the specified data. If the list is empty (i.e. the head is null
), the new node becomes the head of the list. Otherwise, the method traverses the list starting from the head, and finds the last node. The next
field of the last node is set to the new node, making it the new last node.search
method, the method traverses the list starting from the head, and for each node, it checks if the data
field of the node is equal to the search value. If it is, the method returns true
. If the method reaches the end of the list without finding the search value, it returns false
.display
method, the method traverses the list starting from the head, and prints the data of each node.main
method, the program creates a new SinglyLinkedList
object, adds some nodes to the list, displays the list, and searches for an element in the list. The search value is specified as the variable searchValue
. If the element is present in the list, the program prints a message indicating that it is present. If the element is not present in the list, the program prints a message indicating that it is not present.