Python 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 function should return false. If key to be searched is 14, then the function should return true.
Iterative Solution:
1) Initialize a node pointer, current = head.
2) Do following while current is not NULL
a) current->key is equal to the key being searched return true.
b) current = current->next
3) Return false
Following is iterative implementation of above algorithm to search a given key.
Python
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def search( self , x):
current = self .head
while current ! = None :
if current.data = = x:
return True
current = current. next
return False
if __name__ = = '__main__' :
llist = LinkedList()
llist.push( 10 );
llist.push( 30 );
llist.push( 11 );
llist.push( 21 );
llist.push( 14 );
if llist.search( 21 ):
print ( "Yes" )
else :
print ( "No" )
|
Output:
Yes
Time Complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Recursive Solution:
bool search(head, x)
1) If head is NULL, return false.
2) If head's key is same as x, return true;
3) Else return search(head->next, x)
Following is the recursive implementation of the above algorithm to search a given key.
Python
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def search( self , li, key):
if ( not li):
return False
if (li.data = = key):
return True
return self .search(li. next , key)
if __name__ = = '__main__' :
li = LinkedList()
li.push( 1 )
li.push( 2 )
li.push( 3 )
li.push( 4 )
key = 4
if li.search(li.head,key):
print ( "Yes" )
else :
print ( "No" )
|
Output:
Yes
Time Complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(n), for recursive call stack where n represents the length of the given linked list.
Please refer complete article on Search an element in a Linked List (Iterative and Recursive) for more details!
Last Updated :
15 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...