Arrays & Linked Lists


Shared context
Write a constant-time algorithm to insert data D just before a node whose address p is given in a singly linked list. State any limitation of the method.
Answer & solution
Answer: Copy p’s old payload into a new successor, then store D at p; this inserts the value in sequence but changes node identity. (no official key was published)
With only p and no predecessor, one cannot in general redirect the predecessor’s next pointer in constant time while preserving the identity and payload of the existing node p. The standard answer implements insertion in the logical sequence by moving p’s old payload one node forward:
insert_before_value(p, D):
require p != NULL
q := allocate_node() // assumed O(1); handle allocation failure
q.data := p.data
q.next := p.next
p.data := D
p.next := q
return p // address now containing the inserted valueBefore: ... → p:[old] → successor After: ... → p:[D] → q:[old] → successor
The prefix still points to p, so no predecessor lookup is needed. The old data and suffix order are preserved. The method also works when p is the head or the tail. If an external tail pointer is maintained and p was the tail, update tail:=q.
The number of pointer and fixed-size data operations is constant. This assumes payload copying and allocation are constant-time. It does not preserve the old element’s address: external references to p now observe D. If “before the node p” literally requires the same p to remain the old node, the requested operation is impossible from p alone in a general singly linked list; supply its predecessor, an incoming-link pointer, or search from the head in O(n).