0
0
DSA Pythonprogramming~30 mins

Search for a Value in Linked List in DSA Python - Build from Scratch

Choose your learning style9 modes available
Search for a Value in Linked List
📖 Scenario: Imagine you have a list of your favorite books arranged one after another. You want to find if a certain book is in your list.
🎯 Goal: You will create a simple linked list of book names and write code to search for a specific book in that list.
📋 What You'll Learn
Create a linked list with exactly these book names in order: 'Harry Potter', 'The Hobbit', '1984', 'Pride and Prejudice', 'To Kill a Mockingbird'
Create a variable called search_book with the value '1984'
Write a function called search_linked_list that takes the head of the linked list and a book name, and returns True if the book is found, otherwise False
Print Found if the book is in the list, or Not Found if it is not
💡 Why This Matters
🌍 Real World
Linked lists are used in many applications like music playlists, photo galleries, and undo features where items are connected in order.
💼 Career
Understanding linked lists and how to search them is a fundamental skill for software developers working with data structures and algorithms.
Progress0 / 4 steps
1
Create the linked list
Create a class called Node with attributes data and next. Then create the linked list with nodes containing these book names in order: 'Harry Potter', 'The Hobbit', '1984', 'Pride and Prejudice', 'To Kill a Mockingbird'. Assign the first node to a variable called head.
DSA Python
Hint

Start by defining the Node class with data and next. Then create each node with the exact book names and link them using the next attribute.

2
Set the book to search for
Create a variable called search_book and set it to the string '1984'.
DSA Python
Hint

Just create a variable named search_book and assign it the string '1984'.

3
Write the search function
Write a function called search_linked_list that takes two parameters: head (the start of the linked list) and target (the book name to find). The function should check each node's data and return True if target is found, otherwise False.
DSA Python
Hint

Use a while loop to go through each node starting from head. Compare current.data with target. Return True if found, else continue. Return False if you reach the end.

4
Print the search result
Use the search_linked_list function with head and search_book. Print 'Found' if the function returns True, otherwise print 'Not Found'.
DSA Python
Hint

Call search_linked_list(head, search_book). Use an if statement to print 'Found' if it returns True, else print 'Not Found'.