Linked List - Question 5 Answers

5.a, 5.b, and 5.c

\begin{algorithm}
\caption{Doubly Linked Lists}
\begin{algorithmic}
\REQUIRE item = item to insert
\REQUIRE predecessor = linked list item that should precede item
\FUNCTION{insert}{item, predecessor}
  \STATE successor $\gets \text{predecessor}_{\text{next}}$
  \STATE $\text{item}_{next} \gets$ address of successor
  \STATE $\text{item}_{previous} \gets$ address of predecessor
  \STATE $\text{predecessor}_{\text{next}} \gets$ address of item
  \STATE $\text{successor}_{\text{previous}} \gets$ address of item
\ENDFUNCTION
\STATE
\REQUIRE item = item to delete
\FUNCTION{delete}{item}
  \STATE successor $\gets \text{item}_{\text{next}}$
  \STATE predecessor $\gets \text{item}_{\text{previous}}$
  \STATE $\text{successor}_{\text{previous}} \gets$ address of predecessor
  \STATE $\text{predecessor}_{\text{next}} \gets$ address of successor
\ENDFUNCTION
\STATE
\REQUIRE head = head of the linked list
\REQUIRE item = item to insert
\REQUIRE index = zero based index indicating where to insert the item
\FUNCTION{insertAt}{head, item, index}
  \IF{index = 0}
    \STATE $\text{item}_{next} \gets$ address of head
    \STATE $\text{head}_{previous} \gets$ address of item
    \STATE head = item
  \ENDIF
  \STATE predecessor $\gets$ head
  \FOR{$i \gets 0$ to index - 1}
      \STATE predecessor $\gets \text{predecessor}_{next}$
  \ENDFOR
  \STATE \CALL{insert}{item, predecessor}
\ENDFUNCTION
\end{algorithmic}
\end{algorithm}

Return to Exercises