DLL Operation: Insert Before
Suppose we want to insert a note before the one pointed to by the reference variable target
:
![](/img/14/2020-10-05-10-03-03.png)
Exercise Complete the implementation of insertBefore
.
public void insertBefore(Node<T> target, T data) {
// TODO Implement me!
}
Hint: Use the following visualization as guidance.
![](/img/14/2020-10-05-10-04-18.png)
Solution
public void insertBefore(Node<T> target, T data) {
Node<T> nodeToInsert = new Node<>(data);
Node<T> prevNode = target.prev;
target.prev = nodeToInsert;
nodeToInsert.next = target;
nodeToInsert.prev = prevNode;
prevNode.next = nodeToInsert;
}
Caution: the implementation above fails to account for edge cases!