Search an element in a linked list

Program to Search an Element in a linked list

Program to Search an element in a linked list is performed in order to find the location of a particular element in the list. Searching any element in the list needs traversing through the list and make the comparison of every element of the list with the specified element. If the element is matched with any of the list element then the location of the element is returned from the function.

Program to Search an element in a linked list is one of the most simple task you  have in a linked list.For example, if the key to be searched is 55 and linked list is 12->24->11->36->48, then function should return false. If key to be searched is 36, then the function should return true. In this section we will learn more about it with a java code and it’s algorithm.

Algorithm.

Step 1– start

Step 2– initialize a class

step 3– int data; node next; node (int d)

Step 4– initialize a linked list class

Step 5– insert a new node // ( int new_node)

Step 6– node new_node = new Node (new_data)

Step 7- make next node as new node // new_node.next = head

Step 8– move head to new Node// head= new_node

Step 10– Check whether the value is present in linked list

Step 11- Initialize current node

Step 12– run a while loop to find data in current node

Step 13– Add a function to test the above functions

Step 14– input a empty linked list

Step 15– Input data in a empty list

Step 16– Print (“yes”) if the searching number is in the given list

Step 17– else // print (“No”)

Step 18– End .

Java program to search an element in linked list

Java Program for an element in a linked list

//Java program to search an element  in linked list 

//Node class
class Node 
{ 
	int data; 
	Node next; 
	Node(int d) 
	{ 
		data = d; 
		next = null; 
	} 
} 

//Linked list class 
class PrepInsta 
{ 
	Node head; //Head of list 

	//Inserts a new node at the front of the list 
	public void push(int new_data) 
	{ 
		//Allocate new node and putting data 
		Node new_node = new Node(new_data); 

		//Make next of new node as head 
		new_node.next = head; 

		//Move the head to point to new Node 
		head = new_node; 
	} 

	//Checks whether the value x is present in linked list 
	public boolean search(Node head, int x) 
	{ 
		Node current = head; //Initialize current 
		while (current != null) 
		{ 
			if (current.data == x) 
				return true; //data found 
			current = current.next; 
		} 
		return false; //data not found 
	} 

	//Driver function to test the above functions 
	public static void main(String args[]) 
	{ 

		//Start with the empty list 
		PrepInsta llist = new PrepInsta(); 

		llist.push(12); 
		llist.push(24); 
		llist.push(36); 
		llist.push(48); 

		if (llist.search(llist.head, 36)) 
			System.out.println("Yes"); 
		else
			System.out.println("No"); 
	} 
} 
    

Output
yes