Bird
0
0
DSA Cprogramming~30 mins

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

Choose your learning style9 modes available
Search for a Value in Linked List
📖 Scenario: You are working with a simple linked list that stores numbers. You want to find out if a certain number is present in the list.
🎯 Goal: Build a program that creates a linked list, sets a target number to search for, searches the linked list for that number, and prints whether the number was found or not.
📋 What You'll Learn
Create a linked list with exactly three nodes containing the values 10, 20, and 30 in that order
Create an integer variable called target and set it to 20
Write a function called search that takes the head of the linked list and the target value, and returns 1 if found, 0 otherwise
Print Found if the target is in the list, otherwise print Not Found
💡 Why This Matters
🌍 Real World
Searching in linked lists is a basic operation used in many software systems where data is stored dynamically, such as in memory management or real-time data processing.
💼 Career
Understanding linked list traversal and search is fundamental for software developers working with low-level data structures, embedded systems, or performance-critical applications.
Progress0 / 4 steps
1
Create the linked list with three nodes
Create a struct called Node with an integer data and a pointer to Node called next. Then create three nodes named node1, node2, and node3. Set their data to 10, 20, and 30 respectively. Link node1.next to node2, node2.next to node3, and node3.next to NULL. Finally, create a pointer head that points to node1.
DSA C
Hint

Remember to define the struct before main. Then create three variables of type struct Node. Set their data and link their next pointers properly.

2
Set the target value to search
Inside main, create an integer variable called target and set it to 20.
DSA C
Hint

Just declare int target = 20; inside main.

3
Write the search function
Write a function called search that takes two parameters: a pointer to Node called head and an integer target. The function should return 1 if target is found in the linked list, otherwise return 0. Use a while loop to traverse the list.
DSA C
Hint

Use a while loop to check each node's data. Return 1 if found, else 0 after the loop.

4
Call search and print the result
Inside main, call the search function with head and target. If it returns 1, print Found. Otherwise, print Not Found.
DSA C
Hint

Use if (search(head, target)) to check the result. Print Found or Not Found accordingly.