Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
0 like 0 dislike
1.3k views
in Data Structures and Algorithms by Goeduhub's Expert (2.2k points)

How to find an element in a linked list? Here We will see Python Program to search an element in a linked list.

Goeduhub's Top Online Courses @Udemy

For Indian Students- INR 360/- || For International Students- $9.99/-

S.No.

Course Name

 Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence || Labeled as Highest Rated Course by Udemy

Apply Coupon

2.

Complete Machine Learning & Data Science with Python| ML A-Z Apply Coupon

3.

Complete Python Programming from scratch | Python Projects Apply Coupon
    More Courses

1 Answer

0 like 0 dislike
by Goeduhub's Expert (2.2k points)
edited by
 
Best answer

search an element in a linkedlist

1) Search an element in LinkedList (iterative approach)

There are various steps included in the iterative approach for search an element in a linked list and they are as follows:

Step:1 Initialize node pointer current=head

Step:2 As current-> key is not equal to given key,current=current->next(2nd node).

Step:3 As current->key is not equal to given key,current=current->next(3rd node).

Step:4 As current->key is equal to a given key,return True.

# Node class 

class Node:

    # Function to initialize the node object 

    def __init__(selfdata=Nonenext=None):

        self.data = data # Assign data

        self.next = next # Initialize next as null 

# Linked List class 

class LinkedList:

    # Function to initialize the LinkedList object 

    def __init__(self):

        self.head = None

    # print function prints contents of linked list starting from head

    def print(self):

        # if linked list is empty

        if self.head is None:

            print("Linked list is empty")

            return

        itr = self.head

        #taking empty string and appending values

        llstr = ''

        while itr:

            llstr += str(itr.data)+' --> '

            itr = itr.next

        print(llstr)

    # Function to insert a new node at the beginning

    def insert_at_begining(selfdata):

        node = Node(data, self.head)

        self.head = node

       

    # This Function checks whether the value x present in the linked list  

    def search_element(self,x): 

  

        # Initialize itr to head 

        itr = self.head

        count=0

        # loop till itr not equal to None 

        while itr!=None

            if itr.data == x: 

                return count # data found 

            itr = itr.next

            count=count+1

  

        return False # Data Not found 

# Code execution starts here     

if __name__ == '__main__':

    ll = LinkedList()

    

    ll.insert_at_begining(10)

    ll.insert_at_begining(20)

    ll.insert_at_begining(30)

    ll.insert_at_begining(40)

    

    print ("Created Linked List: ")

    ll.print()

    result=ll.search_element(20)

    if (result>=0):

      print("element found in Linkedlist at %d index",result)

    else:

      print("element not found")

2) Search an element in LinkedList (Recursive approach)

Various steps included in this approach are as follows:

Step:1 Head is not Null,head->key is not equal to given key.Therefore,search(head->next,key)is returned.

Step:2 Again Head is not Null,head->key is not equal to given key.Therefore,search(head->next,key)is returned.

Step:3 Again Head is not Null and head->key is equal to given key.Therefore,True is returned.

# Node class 

class Node:

    # Function to initialize the node object 

    def __init__(selfdata=Nonenext=None):

        self.data = data # Assign data

        self.next = next # Initialize next as null 

# Linked List class 

class LinkedList:

    # Function to initialize the LinkedList object 

    def __init__(self):

        self.head = None

    # print function prints contents of linked list starting from head

    def print(self):

        # if linked list is empty

        if self.head is None:

            print("Linked list is empty")

            return

        itr = self.head

        #taking empty string and appending values

        llstr = ''

        while itr:

            llstr += str(itr.data)+' --> '

            itr = itr.next

        print(llstr)

    # Function to insert a new node at the beginning

    def insert_at_begining(selfdata):

        node = Node(data, self.head)

        self.head = node

       

    # This Function checks whether the value x present in the linked list  

    def search_element(self,itr,x): 

        # if linked list is empty

        if itr is None:

          print("Linked list is empty")

          return False

     

        # If key is present in current node, return true 

        if(itr.data == x): 

            return True

        # Recur for remaining list 

        return self.search_element(itr.next,x) 

        

# Code execution starts here     

if __name__ == '__main__':

    ll = LinkedList()

    

    ll.insert_at_begining(10)

    ll.insert_at_begining(20)

    ll.insert_at_begining(30)

    ll.insert_at_begining(40)

    

    print ("Created Linked List: ")

    ll.print()

    result=ll.search_element(ll.head,20)

    if (result):

      print("element found in Linkedlist")

    else:

      print("element not found")

3.3k questions

7.1k answers

394 comments

4.6k users

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...