Search for a value in Linked List

Linked lists are made up of a sequence of nodes where each node links to the next one, forming a chain-like structure. Searching for a value in a linked list involves visiting each node in the list in sequence, access its value and checking if it is equal to the desired value. We continue doing this until reaching the end of the list or until we find the desired node.

Algorithm

  1. Start at the head (first node) of the linked list.
  2. Compare the value of the current node with the target value you are searching for.
  3. If the values match, the search is successful, and you have found the target value.
  4. If the values do not match, move to the next node in the list by following the reference (pointer) to the next node.
  5. Repeat steps 2-4 until either the target value is found or the end of the list is reached (the next pointer is null).
  6. If the target value is not found after reaching the end of the list, the search is unsuccessful.

The time complexity of this search algorithm is O(N), where N is the number of nodes in the linked list. This is because, in the worst case, you may need to traverse the entire list to find the target value or reach the end of the list.

Code

Below is the code to iterate through all nodes in a linked list while printing the values in order.


# Node class to store a item/value and link to the next node
class Node:
  def __init__(self, value):
    self.value = value
    self.next = None

# Function to create a sample linked list with 4 nodes
def make_linked_list():
  # Create the nodes first before linking them
  node1 = Node(1)
  node2 = Node(2)
  node3 = Node(3)
  node4 = Node(4)
  
  # Let us now link/chain the nodes in order
  # to form a linked list
  node1.next = node2
  node2.next = node3
  node3.next = node4
  node4.next = None

  # First node is the head node of the linked list
  head = node1
  return head

# Function to search for a value in given linked list
# Returns the node with search value if search succeeds
# Otherwise returns None
def search_value(head_node, value):
  cur_node = head_node
  # Iterate through all nodes until we reach tail node
  while cur_node != None:
    if cur_node.value == value:
      print("Found a matching node for value:", value)
      return cur_node
    cur_node = cur_node.next
  
  # Return None if we did not find a matching element
  print("Couldn't find a matching node for value:", value)
  return None

# Let's now test the search function
head_node = make_linked_list()
node = search_value(head_node, 2)
node = search_value(head_node, 19)