Given the linked list: 1 -> 2 -> 3 -> 4 -> null, what will be the output of searching for value 3?
class Node: def __init__(self, val): self.val = val self.next = None def search(head, target): current = head while current: if current.val == target: return True current = current.next return False # Create linked list head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) result = search(head, 3) print(result)
Check if the search function returns a boolean True or the string 'true'.
The search function returns the boolean value True when the target is found. Python booleans are capitalized: True.
Given the linked list: 5 -> 10 -> 15 -> null, what will be the output of searching for value 7?
class Node: def __init__(self, val): self.val = val self.next = None def search(head, target): current = head while current: if current.val == target: return True current = current.next return False # Create linked list head = Node(5) head.next = Node(10) head.next.next = Node(15) result = search(head, 7) print(result)
What does the function return if the target is not found?
The function returns False if the target value is not found in the linked list.
Consider this code snippet for searching a value in a linked list. What error will it raise when run?
class Node: def __init__(self, val): self.val = val self.next = None def search(head, target): current = head while current.next: if current.val == target: return True current = current.next return False head = Node(1) head.next = Node(2) head.next.next = Node(3) print(search(head, 3))
Check the loop condition and what happens when current is the last node.
The loop condition 'while current.next' skips checking the last node's value. When current becomes the last node, current.next is None, so the loop ends without checking the last node. But if the target is the last node's value, it will not be found. No error is raised, but the function returns False incorrectly.
Given the linked list: 4 -> 7 -> 9 -> 12 -> null, how many nodes does the search function check when searching for value 4?
class Node: def __init__(self, val): self.val = val self.next = None def search(head, target): current = head count = 0 while current: count += 1 if current.val == target: return count current = current.next return count head = Node(4) head.next = Node(7) head.next.next = Node(9) head.next.next.next = Node(12) result = search(head, 4) print(result)
Think about where the target value is in the list.
The target value 4 is at the first node, so the search checks only one node before finding it.
What is the time complexity of searching for a value in a singly linked list with n nodes?
Think about how nodes are connected and how you access them.
In a singly linked list, nodes are connected one after another. To find a value, you may need to check each node one by one, so the time complexity is O(n).