Search an element in a Linked List ( Iterative and Recursive ) | Node class ; Linked list class ; Head of list ; Inserts a new node at the front of the list ; Allocate new node and putting data ; Make next of new node as head ; Move the head to point to new Node ; Checks whether the value x is present in linked list ; Base case ; If key is present in current node , return true ; Recur for remaining list ; Driver function to test the above functions ; Start with the empty list ; Use push ( ) to construct below list 14 -> 21 -> 11 -> 30 -> 10
class Node { int data ; Node next ; Node ( int d ) { data = d ; next = null ; } } class LinkedList { Node head ; public void push ( int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } public boolean search ( Node head , int x ) { if ( head == null ) return false ; if ( head . data == x ) return true ; return search ( head . next , x ) ; } public static void main ( String args [ ] ) { LinkedList llist = new LinkedList ( ) ; llist . push ( 10 ) ; llist . push ( 30 ) ; llist . push ( 11 ) ; llist . push ( 21 ) ; llist . push ( 14 ) ; if ( llist . search ( llist . head , 21 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }