[Approach 1] Iterative Approach - O(n) Time and O(1) Space
The idea is to traverse all the nodes of the linked list, starting from the head. While traversing, if we find a node whose value is equal to key then print "Yes", otherwise print "No".
Step by Step Approach
Initialize a node pointer, curr = head.
Do following while current is not NULL => If the current value (i.e., curr->key) is equal to the key being searched return true. => Otherwise, move to the next node (curr = curr->next).
If the key is not found, return false
C++
#include<iostream>usingnamespacestd;// a linked list nodeclassNode{public:intdata;Node*next;// constructor to initialize a new node with dataNode(intx){data=x;next=nullptr;}};// checks whether key is present in linked listboolsearchKey(Node*head,intkey){// initialize curr with the head of linked listNode*curr=head;// iterate over all the nodeswhile(curr!=NULL){// If the current node's value is equal to key,// return trueif(curr->data==key)returntrue;// move to the next nodecurr=curr->next;}// if there is no node with value as key, return falsereturnfalse;}intmain(){// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);// key to search in the linked listintkey=5;if(searchKey(head,key))cout<<"true";elsecout<<"false";return0;}
C
#include<stdbool.h>#include<stdio.h>#include<stdlib.h>// Define a linked list nodestructNode{intdata;structNode*next;};// Function to create a new nodestructNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->next=NULL;returnnewNode;}// Function to search for a key in the linked listboolsearchKey(structNode*head,intkey){structNode*curr=head;while(curr!=NULL){if(curr->data==key)returntrue;curr=curr->next;}returnfalse;}intmain(){// Create a linked list: 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);intkey=5;if(searchKey(head,key))printf("true\n");elseprintf("false\n");return0;}
Java
// a Linked List NodeclassNode{intdata;Nodenext;// constructor to initialize a new node with dataNode(intx){data=x;next=null;}}publicclassGFG{// checks whether key is present in linked liststaticbooleansearchKey(Nodehead,intkey){// initialize curr with the head of linked listNodecurr=head;// iterate over all the nodeswhile(curr!=null){// if the current node's value is equal to key,// return trueif(curr.data==key)returntrue;// Move to the next nodecurr=curr.next;}// if there is no node with value as key, return// falsereturnfalse;}publicstaticvoidmain(String[]args){// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);// key to search in the linked listintkey=5;if(searchKey(head,key))System.out.println("true");elseSystem.out.println("false");}}
Python
# a Linked List NodeclassNode:# constructor to intialize a node with datadef__init__(self,x):self.data=xself.next=None# checks whether key is present in linked listdefsearch_key(head,key):# initialize curr with the head of linked listcurr=head# iterate over all the nodeswhilecurrisnotNone:# if the current node's value is equal to key,# return trueifcurr.data==key:returnTrue# move to the next nodecurr=curr.next# if there is no node with value as key, return falsereturnFalseif__name__=="__main__":# create a hard-coded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)# key to search in the linked listkey=5ifsearch_key(head,key):print("true")else:print("false")
C#
usingSystem;// a Linked List NodeclassNode{publicintdata;publicNodenext;// constructor to initialize a new node with datapublicNode(intx){data=x;next=null;}}classGFG{// checks whether key is present in linked liststaticboolsearchKey(Nodehead,intkey){// initialize curr with the head of linked listNodecurr=head;// iterate over all the nodeswhile(curr!=null){// if the current node's value is equal to key,// return trueif(curr.data==key)returntrue;// move to the next nodecurr=curr.next;}// if there is no node with value as key, return// falsereturnfalse;}staticvoidMain(){// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);// key to search in the linked listintkey=5;if(searchKey(head,key))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
classNode{// constructor to initialize a new node with dataconstructor(x){this.data=x;this.next=null;}}// checks whether key is present in linked listfunctionsearchKey(head,key){// initialize curr with the head of linked listletcurr=head;// iterate over all the nodeswhile(curr!==null){// if the current node's value is equal to key,// return trueif(curr.data===key)returntrue;// move to the next nodecurr=curr.next;}// if there is no node with value as key, return falsereturnfalse;}// Driver code// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);// key to search in the linked listletkey=5;if(searchKey(head,key))console.log("true");elseconsole.log("false");
Output
true
[Approach 2] Recursive Approach - O(n) Time and O(n) Space
The idea is to recursively traverse all the nodes starting from the head of linked list. For any node, if the value is equal to key, then return true. Otherwise, recursively search the next node. If at any point the head reaches NULL, it means that we have reached the end of linked list so return false.
Step by Step Approach
If the head is NULL, return false.
If the head's key is the same as X, return true;
Else recursively search in the next node.
C++
#include<iostream>usingnamespacestd;// Linked List NodeclassNode{public:intdata;Node*next;// constructor to initialize a new node with dataNode(intx){data=x;next=nullptr;}};// checks whether the key is present in linked listboolsearchKey(Node*head,intkey){// base caseif(head==nullptr)returnfalse;// if key is present in current node, return trueif(head->data==key)returntrue;// recur for remaining listreturnsearchKey(head->next,key);}intmain(){// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);// Key to search in the linked listintkey=5;if(searchKey(head,key))cout<<"true";elsecout<<"false";return0;}
C
#include<stdbool.h>#include<stdio.h>#include<stdlib.h>// Linked list nodestructNode{intdata;structNode*next;};// Function to create a new nodestructNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->next=NULL;returnnewNode;}// Recursive function to search for a key in the linked listboolsearchKey(structNode*head,intkey){// Base case: list is emptyif(head==NULL)returnfalse;// If key is found at current nodeif(head->data==key)returntrue;// Recur for the rest of the listreturnsearchKey(head->next,key);}intmain(){// Create a hard-coded linked list: 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);intkey=5;if(searchKey(head,key))printf("true\n");elseprintf("false\n");return0;}
Java
// a Linked List NodeclassNode{intdata;Nodenext;// constructor to initialize a new node with dataNode(intx){data=x;next=null;}}publicclassGFG{// checks whether the key is present in linked liststaticbooleansearchKey(Nodehead,intkey){// base caseif(head==null)returnfalse;// if key is present in current node, return trueif(head.data==key)returntrue;// recur for remaining listreturnsearchKey(head.next,key);}publicstaticvoidmain(String[]args){// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);// Key to search in the linked listintkey=14;if(searchKey(head,key))System.out.println("true");elseSystem.out.println("false");}}
Python
# a Linked List NodeclassNode:# constructor to initialize a new node with datadef__init__(self,x):self.data=xself.next=None# checks whether the key is present in linked listdefsearchKey(head,key):# base caseifheadisNone:returnFalse# if key is present in current node, return trueifhead.data==key:returnTrue# recur for remaining listreturnsearchKey(head.next,key)if__name__=="__main__":# create a hard-coded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)# key to search in the linked listkey=5ifsearchKey(head,key):print("true")else:print("false")
C#
usingSystem;// a Linked List NodeclassNode{publicintdata;publicNodenext;// constructor to initialize a new node with datapublicNode(intx){data=x;next=null;}}// checks whether the key is present in linked listclassGFG{// checks whether the key is present in linked liststaticboolsearchKey(Nodehead,intkey){// base caseif(head==null)returnfalse;// if key is present in current node, return trueif(head.data==key)returntrue;// recur for remaining listreturnsearchKey(head.next,key);}staticvoidMain(){// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);// key to search in the linked listintkey=5;if(searchKey(head,key))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// a Linked List NodeclassNode{// constructor to initialize a new node with dataconstructor(x){this.data=x;this.next=null;}}// checks whether the key is present in linked listfunctionsearchKey(head,key){// base caseif(head===null)returnfalse;// if key is present in current node, return trueif(head.data===key)returntrue;// recur for remaining listreturnsearchKey(head.next,key);}// Driver Code// create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);// key to search in the linked listletkey=5;if(searchKey(head,key))console.log("true");elseconsole.log("false");