Write a Java program to check if a particular element exists in a linked list
The Java code provided demonstrates how to use the contains() method in a linked list to check if an element is present in the list or not.
- The code defines a class named Check_Element with a main method, which serves as the entry point for the Java program.
- Inside the main method, a new LinkedList object named fru_list is created with a type parameter of String, indicating that it will store strings as its elements.
- Strings such as "Papaya", "Mulberry", "Apple", etc., are added to the fru_list using the add method, which appends the elements to the end of the list.
- The System.out.println statement is used to print the initial contents of the fru_list before any modifications.
- The contains() method is called on the fru_list with the argument "Cherry" to check if the element "Cherry" is present in the list. If the element is present, the first if block will be executed, and a message "Fruit Cherry is Present.." will be printed. Otherwise, the else block will be executed, and a message "Fruit Cherry is Not Present.." will be printed.
- Similarly, the contains() method is called again on the fru_list with the argument "Guava" to check if the element "Guava" is present in the list. If the element is present, the second if block will be executed, and a message "Fruit Guava is Present.." will be printed. Otherwise, the second else block will be executed, and a message "Fruit Guava is Not Present.." will be printed.
- The output of the program will be the initial contents of the fru_list printed on the first line, followed by the messages indicating if the elements "Cherry" and "Guava" are present or not in the list.
Source Code
import java.util.*;
public class Check_Element
{
public static void main(String[] args)
{
LinkedList <String> fru_list = new LinkedList <String> ();
fru_list.add("Papaya");
fru_list.add("Mulberry");
fru_list.add("Apple");
fru_list.add("Banana");
fru_list.add("Cherry");
fru_list.add("Watermelon");
System.out.println("Given linked list: " + fru_list);
if (fru_list.contains("Cherry"))
{
System.out.println("Fruit Cherry is Present..");
}
else
{
System.out.println("Fruit Cherry is Not Present..");
}
if (fru_list.contains("Guava"))
{
System.out.println("Fruit Guava is Present..");
}
else
{
System.out.println("Fruit Guava is Not Present..");
}
}
}
Output
Given linked list: [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]
Fruit Cherry is Present..
Fruit Guava is Not Present..