Python Program For Searching An Element In A Linked List
Last Updated :
15 Jun, 2022
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
# Iterative Python program to search
# an element in linked list
# Node class
class Node:
# Function to initialise the
# node object
def __init__(self, data):
# Assign data
self.data = data
# Initialize next as null
self.next = None
# Linked List class
class LinkedList:
def __init__(self):
# Initialize head as None
self.head = None
# This function insert a new node at the
# beginning of the linked list
def push(self, new_data):
# Create a new Node
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# This Function checks whether the value
# x present in the linked list
def search(self, x):
# Initialize current to head
current = self.head
# Loop till current not equal to None
while current != None:
if current.data == x:
# Data found
return True
current = current.next
# Data Not found
return False
# Driver code
if __name__ == '__main__':
# Start with the empty list
llist = LinkedList()
# Use push() to construct list
# 14->21->11->30->10
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if llist.search(21):
print("Yes")
else:
print("No")
# This code is contributed by Ravi Shankar
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
# Recursive Python program to
# search an element in linked list
# Node class
class Node:
# Function to initialize
# the node object
def __init__(self, data):
# Assign data
self.data = data
# Initialize next as null
self.next = None
class LinkedList:
def __init__(self):
# Initialize head as None
self.head = None
# This function insert a new node at
# the beginning of the linked list
def push(self, new_data):
# Create a new Node
new_node = Node(new_data)
# Make next of new Node as head
new_node.next = self.head
# Move the head to
# point to new Node
self.head = new_node
# Checks whether the value key
# is present in linked list
def search(self, li, key):
# Base case
if(not li):
return False
# If key is present in
# current node, return true
if(li.data == key):
return True
# Recur for remaining list
return self.search(li.next, key)
# Driver Code
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")
# This code is contributed by Manoj Sharma
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!
Similar Reads
Python 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->2
3 min read
Python Program For Writing A Function To Delete A Linked List Algorithm For Python:In Python, automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null. Implementation:Â Python3 # Python3 program to delete all # the nodes of singly linked list # Node class class Node: # Function to initialize the # node object de
2 min read
Python 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
Python Program For Deleting A Node In A Doubly Linked List Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
4 min read
Python Program For Finding The Middle Element Of A Given Linked List Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
4 min read
Python Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
4 min read
Python program to find String in a List Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, weâll explore several methods to find a string in a list, starting from the most e
3 min read
Python Program For Moving All Occurrences Of An Element To End In A Linked List Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7
6 min read
Python Program For Swapping Nodes In A Linked List Without Swapping Data Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15-
5 min read
Python Program For Deleting A Linked List Node At A Given Position Given a singly linked list and a position, delete a linked list node at the given position. Example: Input: position = 1, Linked List = 8->2->3->1->7 Output: Linked List = 8->3->1->7 Input: position = 0, Linked List = 8->2->3->1->7 Output: Linked List = 2->3->1
3 min read