QUESTION 19
How do you search a singly linked list by key?
2 marksAnswer
Start at head and follow next links, comparing each node’s key. Stop at a match or NULL.
QUESTION 19
Start at head and follow next links, comparing each node’s key. Stop at a match or NULL.
QUESTION 20
A linked list can be searched or counted by visiting its nodes in forward order.
Start count at zero. Increment it for every visited node. The empty list produces zero. If size is stored in the list descriptor instead, update it consistently on every successful insertion and deletion; a stale cached count is not useful.
For 10 → 20 → 30, a search for 20 makes two comparisons. A search for 99 visits all three nodes before reporting failure. Returning a node pointer does not transfer ownership automatically; its validity ends if the node is later removed or the list is destroyed.
A first-node match is O(1). The worst case is O(n), including a missing key. Counting without a cached size also takes O(n). A fixed current pointer and counter use O(1) auxiliary space.
Sorted list values can allow a forward scan to stop early once it passes the key, but ordinary linked nodes still do not provide constant-time middle access. The array binary-search algorithm cannot simply assume it can jump to any linked-list midpoint in O(1).