712251. Search in Linked List

Easy

Search in Linked List

Summary

The problem "Search in Linked List" involves searching for a specific element within a linked list. The goal is to find the node containing the target value and return its address or position within the list. This problem requires understanding of linked lists, traversal techniques, and basic algorithmic concepts.

Detailed Explanation

To solve this problem, we'll utilize a simple traversal technique, traversing through the linked list from head to tail until we find the desired element. We'll keep track of the node's value and return its address when found.

Here's a step-by-step breakdown of the solution:

  1. Initialize a pointer current to point to the head of the linked list.
  2. Traverse through the linked list by moving current one step at a time until it reaches the end or finds the target element.
  3. At each step, compare the value stored in current->data with the target value.
  4. If the values match, return the address of current.
  5. Continue traversing until we reach the end of the list or find the target element.

Time Complexity: O(n), where n is the number of nodes in the linked list. Space Complexity: O(1), as we only use a constant amount of space to store the pointers and variables.

Optimized Solutions

Here are optimized solutions for various programming languages:

Java

View on GeeksforGeeks
public Node search(Node head, int target) {
    Node current = head;
    while (current != null && current.data != target) {
        current = current.next;
    }
    return current;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.