862 views
Consider a singly linked list having $n$ nodes. The data items $d_1, d_2, \dots d_n$ are stored in these $n$ nodes. Let $X$ be a pointer to the $j^{th}$ node $(1 \leq j \leq n)$ in which $d_j$ is stored. A new data item $d$ stored in node with address $Y$ is to be inserted. Give an algorithm to insert $d$ into the list to obtain a list having items $d_1, d_2, \dots, d_{j}, d,\dots, d_n$ in order without using the header.
in DS
recategorized | 862 views

Following $2$ lines are enough to realise above constraint :->>

1. Y->next = X-> next 2. X->next = Y

by Boss (23.8k points)
edited by
+3

d->next = dj->next

dj->next = d

these steps are mandatory for the algorithm :
\begin{align*} temp &= X \rightarrow next\\ X \rightarrow next &= Y \\ Y \rightarrow next &= temp \end{align*}

by Boss (30.7k points)

As one can notice all the answers given are trying to insert d at (j+1)th index instead of jth index as asked in the question ( see the position of d in the sequence given in last line).

I have used the following approach. by (13 points)