Skip to study material
← Question index

QUESTION 20

Explain searching and counting nodes in a singly linked list.

5 marks

Answer in brief

A linked list can be searched or counted by visiting its nodes in forward order.

Search algorithm

  1. Set current = head.
  2. While current exists, compare its data with key.
  3. Return the matching node or a success result when equal.
  4. Otherwise advance to next; report failure after reaching NULL.

Counting

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.

Example

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.

Complexity

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.

Order and access

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).