GATE / CS ARCHIVE

GATE CSE 1993 / QUESTION 13

Insert before a singly linked-list node

Data Structures · Arrays & Linked Lists · Full GATE CSE 1993 paper

GATE 1993, Q13 5 marks · Descriptive
Report issue

Arrays & Linked Lists

Question 13, GATE 1993: A singly linked list contains d1,...,dn. X points to node j (1<=j<=n). A new node Y contains item d. Give an insertion algorithm without using the header. Both inspected reproductions print a desired sequence d1,...,d(j-1),dj,...,dn that omits the new d; the intended insert-before-X sequence d1,...,d(j-1),d,dj,...,dn is used below as an explicit interpretation.
Tap to enlarge
Answer & solution

Answer: Exchange X.data and Y.data, then set Y.next=X.next and X.next=Y; conditional on the intended insert-before-X interpretation and movable data. (no official key was published)

Without a predecessor pointer or access to the header, ordinary link insertion immediately before the physical node X is unavailable. But the requested data sequence can be achieved by exchanging data with the fresh node and linking that node after X. Assume X is non-null, Y is a fresh detached node distinct from all current nodes, and data fields may be copied:

procedure insert_before_by_value(X,Y):
    temp := X.data
    X.data := Y.data
    Y.data := temp
    Y.next := X.next
    X.next := Y

Initially X contains dj and Y contains d. After the exchange X contains d and Y contains dj. Y.next is then set to the former successor of X, and X.next is changed to Y. The local chain is now predecessor -> X(d) -> Y(dj) -> old successor. All nodes preceding X remain unchanged; any header already pointing to X still points to the first node. Therefore the data sequence becomes exactly the interpreted target. Saving the old successor before overwriting X.next is essential; reversing the last two operations would set Y.next=Y and create a cycle.

This also handles j=1 without changing the header, because X remains the physical first node but now carries d. For j=n, the old successor is null, so Y becomes the new last node. There are a constant number of field operations, giving O(1) time and O(1) extra space.

The method preserves value order, not node-to-value identity: an external pointer to X will now observe d, and dj moves to Y. If data cannot be moved or the physical new node Y must precede X, the supplied information is insufficient in a singly linked list, particularly when X is the head. That stronger requirement needs header/predecessor access or a changed representation. Finally, the printed sequence itself contains no d, so it cannot literally describe successful insertion; the source defect is retained rather than represented as a verified correction.

Original paper, page 11