Java Program to Search an Element in a Linked List
Last Updated :
21 Aug, 2022
Prerequisite: LinkedList in java
LinkedList is a linear data structure where the elements are not stored in contiguous memory locations. Every element is a separate object known as a node with a data part and an address part. The elements are linked using pointers or references. Linked Lists are preferred over arrays in case of deletions and insertions as they take O(1) time for the respective operations.
Advantages of Linked List:
- Insertions and deletions take O(1) time.
- Dynamic in nature.
- Memory is not contiguous.
Syntax:
LinkedList<ClassName> variableName = new LinkedList<>();
Example:
LinkedList<Integer> ll = new LinkedList<>();
Task:
Search for an element in a linked list.
Approach:
When the linked list is provided to us directly, we can use a for loop to traverse through the list and find the element. In case, if we are not allowed to use pre-built libraries, we need to create our very own linked list and search for the element.
Examples:
Input: ll1 = [10, 20, 30, -12, 0, 23, -2, 12]
element = 23
Output: 5
Input: ll2 = [1, 2, 3, 4, 5]
element = 3
Output: 2
The following are the two methods with which we can search for an element in a Linked List.
Method 1: When we are allowed to use in-built libraries
- First, a Linked list is initialized.
- A for loop is used to traverse through the elements present in the Linked List.
Below is the implementation of the above approach:
Java
// Java Program to find an element in a Linked List
// Importing the Linked List class
import java.util.LinkedList;
class SearchInALinkedList {
public static void main(String[] args)
{
// Initializing the Linked List
LinkedList<Integer> ll = new LinkedList<>();
// Adding elements to the Linked List
ll.add(1);
ll.add(2);
ll.add(3);
ll.add(4);
ll.add(5);
ll.add(6);
ll.add(7);
// Element to be searched
int element = 4;
// Initializing the answer to the index -1
int ans = -1;
// Traversing through the Linked List
for (int i = 0; i < ll.size(); i++) {
// Eztracting each element in
// the Linked List
int llElement = ll.get(i);
// Checking if the extracted element is equal to
// the element to be searched
if (llElement == element) {
// Assigning the index of the
// element to answer
ans = i;
break;
}
}
// Checking if the element is present in the Linked
// List
if (ans == -1) {
System.out.println("Element not found");
}
else {
System.out.println(
"Element found in Linked List at " + ans);
}
}
}
OutputElement found in Linked List at 3
Time Complexity: O(n) where n is the number of elements present in the linked list.
Auxiliary Space: O(1)
Method 2: When we are not allowed to use in-built libraries
- First, create a generic node class.
- Create a LinkedList class and initialize the head node to null.
- Create the required add and search functions.
- Initialize the LinkedList in the main method.
- Use the search method to find the element.
Below is the implementation of the above approach:
Java
// A Generic Node class is used to create a Linked List
class Node<E> {
// Data Stored in each Node of the Linked List
E data;
// Pointer to the next node in the Linked List
Node<E> next;
// Node class constructor used to initializes the data
// in each Node
Node(E data) { this.data = data; }
}
class LinkedList<E> {
// Points to the head of the Linked
// List i.e the first element
Node<E> head = null;
int size = 0;
// Addition of elements to the tail of the Linked List
public void add(E element)
{
// Checks whether the head is created else creates a
// new one
if (head == null) {
head = new Node<>(element);
size++;
return;
}
// The Node which needs to be added at
// the tail of the Linked List
Node<E> add = new Node<>(element);
// Storing the instance of the
// head pointer
Node<E> temp = head;
// The while loop takes us to the tail of the Linked
// List
while (temp.next != null) {
temp = temp.next;
}
// New Node is added at the tail of
// the Linked List
temp.next = add;
// Size of the Linked List is incremented as
// the elements are added
size++;
}
// Searches the Linked List for the given element and
// returns it's particular index if found else returns
// -1
public int search(E element)
{
if (head == null) {
return -1;
}
int index = 0;
Node<E> temp = head;
// While loop is used to search the entire Linked
// List starting from the tail
while (temp != null) {
// Returns the index of that particular element,
// if found.
if (temp.data == element) {
return index;
}
// Gradually increases index while
// traversing through the Linked List
index++;
temp = temp.next;
}
// Returns -1 if the element is not found
return -1;
}
}
public class GFG {
public static void main(String[] args) throws Exception
{
// Initializing the Linked List
LinkedList<Integer> ll = new LinkedList<>();
// Adding elements to the Linked List
ll.add(1);
ll.add(10);
ll.add(12);
ll.add(-1);
ll.add(0);
ll.add(-19);
ll.add(34);
// Element to be searched
int element = -1;
// Searching the Linked
// List for the element
int ans = ll.search(-1);
if (ans == -1) {
System.out.println(
"Element not found in the Linked List");
}
else
System.out.println(
"Element found in the Linked List at "
+ ans);
}
}
OutputElement found in the Linked List at 3
Time Complexity: O(n) where n is the number of elements present in the linked list.
Auxiliary Space: O(1)
Similar Reads
Java Program to Search an Element in a Circular Linked List
A linked list is a kind of linear data structure where each node has a data part and an address part which points to the next node. A circular linked list is a type of linked list where the last node points to the first one, making a circle of nodes. Example: Input : CList = 6->5->4->3->
3 min read
Java Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functi
4 min read
Java Program to Get Elements of a LinkedList
Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList. 1. We can use get(int variable) method to access an element from a specific index of LinkedList: In the given example, we have used
4 min read
Java Program to Implement LinkedList API
Linked List is a part of the Collection framework That is present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure in which the elements are not stored in contiguous locations and every element is a separate object with a data pa
10 min read
Java Program to Search an Element in Vector
A vector in Java is a dynamic array that can be resized as needed. It is synchronized, which means it is safe in multi-threaded programs. To find an element in a Vector we have to loop through its elements to find a match. In this article, we will learn how to search for a component in a Vector usin
3 min read
Java Program to Get the First and the Last Element of a Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The given task is to retrieve the first and the last element of a given linked list. Properties of a Linked ListElements are stored in a non-contiguous manner.Every element is an object whi
4 min read
Java Program To Recursively Linearly Search An Element In An Array
Given an array arr[] of n elements, write a recursive function to search for a given element x in the given array arr[]. If the element is found, return its index otherwise, return -1.Input/Output Example:Input : arr[] = {25, 60, 18, 3, 10}, Element to be searched x = 3Output : 3 (index )Input : arr
3 min read
Adding an Element to the Front of LinkedList in Java
A Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements are linked using pointers and addresses. Each element is known as a node. This article shows how to add an element to the front of LinkedList in Java. Method 1: (Using user-def
3 min read
Java Program to Sort the Elements of the Circular Linked List
In a circular linked list, every node points to its next node in the sequence but the last node points to the first node in the list. Here, Create a circular linked list and sort the circular linked list in ascending order. Circular linked list before sorting: CIRCULAR LINKED LIST Circular linked li
3 min read
Java Program For Deleting A Node In A Linked List
We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a 'key', delete the first occurrence of this key in the linked list. Iterative Method:To delete a node from
3 min read