Find a node with a given value in a singly linked list

This problem asks you to write a function that takes in the head node of a singly linked list and a value, and returns the node with the given value. If the value is not present in the linked list, return null.

Problem

Write a function that takes in the head node of a singly linked list and a value, and returns the node with the given value. If the value is not present in the linked list, return null.
Example input:
1 -> 2 -> 3 -> 4 -> null
3
Example output:
3

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def add_node(self, value):
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
            return
        current_node = self.head
        while current_node.next is not None:
            current_node = current_node.next
        current_node.next = new_node

    def print_list(self):
        current_node = self.head
        while current_node is not None:
            print(current_node.value)
            current_node = current_node.next

    def find_node(self, value):
        current_node = self.head
        while current_node is not None:
            if current_node.value == value:
                return current_node
            current_node = current_node.next
        return None

# Test linked_list = LinkedList()
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)
linked_list.add_node(4)

print(linked_list.find_node(3))
print(linked_list.find_node(5))



In Python write the optimal solution for the problem below. Add a comment explaining the solution and why it is optimal.

Problem:
Write a function that takes in the head node of a singly linked list and a value, and returns the node with the given value. If the value is not present in the linked list, return null.
Example input:
1 -> 2 -> 3 -> 4 -> null
3
Example output:
3


A.I. Evaluation of the Solution

The candidate's solution correctly implements a function to find a node in a singly linked list by its value. The candidate's use of a while loop to iterate through the list is an efficient way to find the desired node. The candidate's solution is optimal in that it correctly implements the function and efficiently iterates through the list.

Evaluated at: 2022-11-18 08:16:10