Skip to main content

Search an Element in Linked List

Problem Statement:​

  • Example:



bool searchElement(SinglyLinkedListNode* head, int target) {
SinglyLinkedListNode* current = head;

// Traverse the list to look for the target
while(current != nullptr) {
if(current->data == target) return true;
current = current->next;
}

return false; // Not found
}


📝 How It Works​

  • We initialize a pointer current at the head.
  • Traverse the list node by node.
  • At each step, check if current->data == target.
  • If found, return true.
  • If we reach the end without finding it, return false.

This is a basic linear search on a linked list.


🧩 Key Logic​

The main condition checked inside the loop:

if(current->data == target) return true;


⏱️ Time & Space Complexity​

MetricValue
🕒 TimeO(N), where N is number of nodes
🧠 SpaceO(1), no extra space used

⚠️ Edge Cases​

  • Empty list → returns false
  • First node is the target → returns immediately
  • Last node is the target → full traversal needed
  • Target not present → returns false

💡 Other Approaches​

ApproachTimeSpaceUse When
Iterative ✅O(N)O(1)Preferred for simplicity
RecursiveO(N)O(N)Good for practice, but inefficient due to stack

  • Find the middle node
  • Detect cycle in a linked list
  • Find N-th node from the end
  • Count frequency of a specific value

🚀 Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚡
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

💡Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→